__str__ 和 __repr__
如果要把一个类的实例变成 __str__,就需要实现特殊方法 __str__:
1 2 3 4 5 6
| class Person(object): def __init__(self, name, gender): self.name = name self.gender = gender def __str__(self): return '(Person: %s, %s)' % (self.name, self.gender)
|
在交互式命令行下用 print :
1 2 3
| >>> p = Person('Bob', 'male') >>> print p (Person: Bob, male)
|
但是,如果直接敲变量 p:
1 2
| >>> p <main.Person object at 0x10c941890>
|
因为 Python 定义了str()和repr()两种方法,__str__用于显示给用户,而__repr__用于显示给开发人员。
有一个偷懒的定义__repr__的方法:
1 2 3 4 5 6 7 8 9 10 11
| class Person(object): def __init__(self, name, gender): self.name = name self.gender = gender def __str__(self): return '(Person: %s, %s)' % (self.name, self.gender) __repr__ = __str__
>>> p = Person("a","b") >>> p (Person: a, b)
|
__cmp__
python2下使用,python3无__cmp__
对 int、str 等内置数据类型排序时,Python的 sorted() 按照默认的比较函数 cmp 排序,但是,如果对一组 Student 类的实例排序时,就必须提供我们自己的特殊方法 __cmp__():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Student(object): def __init__(self, name, score): self.name = name self.score = score def __str__(self): return '(%s: %s)' % (self.name, self.score) __repr__ = __str__
def __cmp__(self, s): if self.name < s.name: return -1 elif self.name > s.name: return 1 else: return 0
|
上述 Student 类实现了__cmp__()方法,__cmp__用实例自身self和传入的实例 s 进行比较,如果 self 应该排在前面,就返回 -1,如果 s 应该排在前面,就返回1,如果两者相当,返回 0。
Student类实现了按name进行排序:
1 2 3
| >>> L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 77)] >>> print(sorted(L)) [(Alice: 77), (Bob: 88), (Tim: 99)]
|
注意: 如果list不仅仅包含 Student 类,则 cmp 可能会报错:
1 2
| L = [Student('Tim', 99), Student('Bob', 88), 100, 'Hello'] print(sorted(L))
|
__len__
如果一个类表现得像一个list,要获取有多少个元素,就得用 len() 函数。
要让 len() 函数工作正常,类必须提供一个特殊方法__len__(),它返回元素的个数。
1 2 3 4 5 6 7 8
| class Students(object): def __init__(self, *args): self.names = args def __len__(self): return len(self.names)
ss = Students('Bob', 'Alice', 'Tim') print(len(ss))
|
运算
Python 提供的基本数据类型 int、float 可以做整数和浮点的四则运算以及乘方等运算。
但是,四则运算不局限于int和float,还可以是有理数、矩阵等。
要表示有理数,可以用一个Rational类来表示:
1 2 3 4
| class Rational(object): def __init__(self, p, q): self.p = p self.q = q
|
p、q 都是整数,表示有理数 p/q。
如果要让Rational进行+运算,需要正确实现__add__:
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Rational(object): def __init__(self, p, q): self.p = p self.q = q def __add__(self, r): return Rational(self.p * r.q + self.q * r.p, self.q * r.q) def __str__(self): return '%s/%s' % (self.p, self.q) __repr__ = __str__
r1 = Rational(1, 3) r2 = Rational(1, 2) print(r1 + r2)
|
四则运算:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| def gcd(a, b): if b == 0: return a return gcd(b, a % b)
class Rational(object): def __init__(self, p, q): self.p = p self.q = q
def __add__(self, r): return Rational(self.p * r.q + self.q * r.p, self.q * r.q)
def __sub__(self, r): return Rational(self.p * r.q - self.q * r.p, self.q * r.q)
def __mul__(self, r): return Rational(self.p * r.p, self.q * r.q)
def __truediv__(self, r): return Rational(self.p * r.q, self.q * r.p)
def __str__(self): g = gcd(self.p, self.q) return f'{self.p / g}/{self.q / g}'
__repr__ = __str__
r1 = Rational(1, 2) r2 = Rational(1, 4) print(r1 + r2) print(r1 - r2) print(r1 * r2) print(r1 / r2)
|
类型转换
Rational类实现了有理数运算,但是,如果要把结果转为 int 或 float 怎么办?
考察整数和浮点数的转换:
1 2 3 4
| >>> int(12.34) 12 >>> float(12) 12.0
|
如果要把 Rational 转为 int,应该使用:
1 2 3
| r = Rational(12, 5) n = int(r)
|
要让 int() 函数正常工作,只需要实现特殊方法__int__(), 同理要让 float() 函数正常工作,只需要实现特殊方法__float__()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| def gcd(a, b): if b == 0: return a return gcd(b, a % b)
class Rational(object): def __init__(self, p, q): self.p = p self.q = q
def __str__(self): g = gcd(self.p, self.q) return f'{self.p / g}/{self.q / g}'
def __float__(self): return float(self.p) / self.q
def __int__(self): return self.p // self.q
__repr__ = __str__
print(Rational(6,8)) print(int(Rational(6,8))) print(float(Rational(6,8))) print(Rational(8,6)) print(int(Rational(8,6))) print(float(Rational(8,6)))
|
@property
举例 Student 类:
1 2 3 4
| class Student(object): def __init__(self, name, score): self.name = name self.score = score
|
当我们想要修改一个 Student 的 score 属性时,可以这么写:
1 2 3 4
| s = Student('Bob', 59) s.score = 60
s.score = 1000
|
但是也可以这么写:
显然,直接给属性赋值无法检查分数的有效性。
如果利用两个方法:
1 2 3 4 5 6 7 8 9 10
| class Student(object): def __init__(self, name, score): self.name = name self.__score = score def get_score(self): return self.__score def set_score(self, score): if score < 0 or score > 100: raise ValueError('invalid score') self.__score = score
|
这样 s.set_score(1000) 就会报错, 达到检查数据的目的。
这种使用 get/set 方法来封装对一个属性的访问在许多面向对象编程的语言中都很常见。
但是写 s.get_score() 和 s.set_score() 没有直接写 s.score 来得直接。
有一个两全其美的方法:
因为Python支持高阶函数,在函数式编程中有装饰器函数,可以用装饰器函数把 get/set 方法“装饰”成属性调用:
1 2 3 4 5 6 7 8 9 10 11 12
| class Student(object): def __init__(self, name, score): self.name = name self.__score = score @property def score(self): return self.__score @score.setter def score(self, score): if score < 0 or score > 100: raise ValueError('invalid score') self.__score = score
|
注意: 第一个score(self)是get方法,用@property装饰,第二个score(self, score)是set方法,用@score.setter装饰,@score.setter是前一个@property装饰后的副产品。
现在,就可以像使用属性一样设置score了:
1 2 3 4 5 6 7 8 9
| >>> s = Student('Bob', 59) >>> s.score = 60 >>> print(s.score) 60 >>> s.score = 1000 Traceback (most recent call last): ... ValueError: invalid score
|
__slot__
由于Python是动态语言,任何实例在运行期都可以动态地添加属性。
如果要限制添加的属性,例如,Student类只允许添加 name、gender和score 这3个属性,就可以利用Python的一个特殊的__slots__来实现。
__slots__是指一个类允许的属性列表:
1 2 3 4 5 6
| class Student(object): __slots__ = ('name', 'gender', 'score') def __init__(self, name, gender, score): self.name = name self.gender = gender self.score = score
|
对实例进行操作:
1 2 3 4 5 6 7
| >>> s = Student('Bob', 'male', 59) >>> s.name = 'Tim' >>> s.score = 99 >>> s.grade = 'A' Traceback (most recent call last): ... AttributeError: 'Student' object has no attribute 'grade'
|
__slots__的目的是限制当前类所能拥有的属性,如果不需要添加任意动态的属性,使用__slots__也能节省内存。
举例:假设Person类通过slots定义了name和gender,在派生类Student中通过slots继续添加score的定义,使Student类可以实现name、gender和score 3个属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Person(object):
__slots__ = ('name', 'gender')
def __init__(self, name, gender): self.name = name self.gender = gender
class Student(Person):
__slots__ = ('score')
def __init__(self, name, gender, score): super(Student, self).__init__(name, gender) self.score = score
s = Student('Bob', 'male', 59) s.name = 'Tim' s.score = 99 print(s.score)
|
__call__
函数也是对象,也可以被调用,所有的函数都是可调用对象。
一个类实例也可以变成一个可调用对象,只需要实现一个特殊方法__call__()。
我们把 Person 类变成一个可调用对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Person(object): def __init__(self, name, gender): self.name = name self.gender = gender
def __call__(self, friend): print(f'name is {self.name}') print(f'friend is {friend}')
p1 = Person("zzz",'male') p1('friend_uuu')
|
单看p1(‘friend_uuu’)无法确定 p1 是一个函数还是一个类实例,所以,在Python中,函数也是对象,对象和函数的区别并不显著。
1 2 3 4 5 6 7 8 9 10
| class Fib(object): def __call__(self, num): a, b, retlist = 0, 1, [] for i in range(num): retlist.append(a) a, b = b, a+b return retlist
f = Fib() print(f(10))
|
Best Practices
- 始终实现
__repr__ 以进行调试
- 使特殊方法与内置类型一致
- 尽可能使用
@property 而不是 get/set 方法
- 适当时使用
@total_ordering 实现比较方法
- 需要时使用
__slots__ 进行内存优化
- 保持特殊方法简单且有针对性
- 彻底记录特殊方法
Common Pitfalls
- 忘记在算术运算中返回新对象
- 未处理比较方法中的极端情况
- 实现
__str__ 而不使用 __repr__
- 在
__init__ 中使用可变默认参数
- 未考虑特殊方法中的类型检查
请记住,特殊方法是功能强大的工具,应谨慎使用。它们允许您使对象的行为像内置类型一样并与 Python 的语法无缝集成,但只有当它们使您的代码更具可读性和可维护性时才应实现它们。