python类用法(二)

简介: python类用法(二)

python类用法(二)

、类的特殊方法

在Python中,有一些特殊的方法(也叫魔术方法或双下划线方法)用于定义类的行为。这些方法通常具有特定的命名格式,如__init____str____eq__等。

1. __init__ 方法

__init__ 方法是一个类的构造函数,当创建类的新实例时自动调用。它通常用于初始化新对象的属性。

python复制代码

 

class Person:

 

def __init__(self, name, age):

 

self.name = name

 

self.age = age

2. __str__ 方法

__str__ 方法返回一个描述对象的字符串,通常用于print函数或字符串格式化。

python复制代码

 

class Person:

 

def __init__(self, name, age):

 

self.name = name

 

self.age = age

 

 

 

def __str__(self):

 

return f"Person(name={self.name}, age={self.age})" 

 

 

 

person = Person("Alice", 30)

 

print(person) # 输出: Person(name=Alice, age=30)

3. __eq__ 方法

__eq__ 方法用于比较两个对象是否相等。

python复制代码

 

class Person:

 

def __init__(self, name, age):

 

self.name = name

 

self.age = age

 

 

 

def __eq__(self, other):

 

if isinstance(other, Person):

 

return self.name == other.name and self.age == other.age

 

return False 

 

 

 

person1 = Person("Alice", 30)

 

person2 = Person("Alice", 30)

 

person3 = Person("Bob", 25)

 

print(person1 == person2) # 输出: True

 

print(person1 == person3) # 输出: False

、类的封装和数据隐藏

类的封装是将数据(变量)和对其操作的方法捆绑在一起,形成一个独立的单元。Python通过约定俗成的命名方式(如使用单个下划线、双个下划线前缀等)来实现数据隐藏。

1. 单个下划线前缀

单个下划线前缀通常表示该属性或方法是“受保护的”或“内部使用的”,但这不是强制性的,外部代码仍然可以访问。

python复制代码

 

class MyClass:

 

def __init__(self):

 

self._private_var = "This is a private variable"

2. 双个下划线前缀

双个下划线前缀会导致Python解释器对属性名称进行变形(名称重整),使得外部代码无法直接访问。这是一种较强的封装方式。

python复制代码

 

class MyClass:

 

def __init__(self):

 

self.__private_var = "This is a truly private variable" 

 

 

 

# 外部代码无法直接访问 __private_var

 

# my_instance._MyClass__private_var # 可以通过这种方式访问,但不建议这样做

 

 

目录
相关文章
|
28天前
|
Python
python基本用法
【9月更文挑战第5天】python基本用法
38 7
|
4天前
|
前端开发 Python
Python编程的面向对象(二)—类的多态
Python编程的面向对象(二)—类的多态
12 7
|
3天前
|
IDE Java 开发工具
Python类与面向对象
Python类与面向对象
|
5天前
|
Python
Python中正则表达式(re模块)用法详解
Python中正则表达式(re模块)用法详解
13 2
|
7天前
|
关系型数据库 MySQL Python
mysql之python客户端封装类
mysql之python客户端封装类
|
8天前
|
Python
python 类中的内置方法
python 类中的内置方法
|
19天前
|
人工智能 数据挖掘 开发者
Python用法
Python用法
23 10
|
5天前
|
Python
Python变量用法——单下划线变量名_ 原创
Python变量用法——单下划线变量名_ 原创
16 0
|
5天前
|
Python
Python变量用法——变量解包
Python变量用法——变量解包
15 0
|
6天前
|
Python
Python类中属性和方法区分3-8
Python类中属性和方法区分3-8
下一篇
无影云桌面