特殊方法是什么
是一种具有特殊魅力的正常方法,python通过这些方法可以赋予你的class魔力。
这些魔法方法 都是以双下划线__作为 前缀和后缀。
初始化
__new__()创造实例, __init__()初始化实例。
__init__() 是一个类 (class) 的第一个方法,也叫构造函数。 是第一个被创建,但不是第一个被执行的。
__new__() 才是最早被调用的方法
__new__(): 先读取参数( 如类名称,args,和kwargs), 然后 new() 方法把这些参数传递给__init__(),__new__(class_name, args, kwargs)__init__(): 类的初始化方法或构造方法, 几乎用于 全局的初始化目的。__init__(slef, args, kwargs)__del__(): 类的析构函数,定义一个对象被垃圾回收的行为。__del__(self)
1 | class SimpleInit: |
算术运算,增量赋值
__add__(self.other) + __iadd__(self.other) +=__sub__(self.other) - __isub__(self.other) -=__mul__(self.other) * __imul__(self.other) *=__floordiv__(self.other) // __ifloordiv__(self.other) //=__div__(self.other) / __idiv__(self.other) /=__mod__(self.other) % __imod__(self.other) %=__and__(self.other) & __iand__(self.other) &=__or__(self.other) | __ior__(self.other) |=__xor__(self.other) ^ __ixor__(self.other) ^=__pow__(self.other) ** __ipow__(self.other) **=__lshift__(self.other) << __ilshift__(self.other) <<=__rshift__(self.other) >> __irshift__(self.other) >>=1
2
3
4
5
6
7
8
9
10
11
12
13
14from dataclasses import dataclass, field
@dataclass
class Simpleadder:
_elements:list = list
def __add__(self, other):
return self._elements + other._elements
a = Simpleadder([1,2,3,4,5])
b = Simpleadder([4,5,6,7,8])
print(a, b) # Simpleadder(_elements=[1, 2, 3, 4, 5]) Simpleadder(_elements=[4, 5, 6, 7, 8])
print(a + b) # [1, 2, 3, 4, 5, 4, 5, 6, 7, 8]
比较运算
python3.7 可使用dataclass
__eq__(self.other) ==__ne__(self.other) !=__lt__(self.other) <__gt__(self.other) >__le__(self.other) <=__ge__(self.other) >=
类型转换
__int__(self)int__long__(self)long__float__(self)float__complex__(self)complex__oct__(self)octal (八进制)__hex__(self)(十六进制)__index__(self)转为int, 当对象被用于切片表达式
最常用
__str__(self)__repr__(self)类似__str__()str()主要用于人类可读, repr() 机器可读__hash__(self)定义了行为调用hash()__len__(self)返回容器长度__getitem__(self)setitem(self)__delitem__(self)定义一个删除一个项目的行为__iter__(self)返回一个迭代容器__call__(self)使实例能够像函数一样被调用,同时不影响实例本身的生命周期
__call__()不影响一个实例的构造和析构。但是__call__()可以用来改变实例的内部成员的值1
2
3
4
5
6
7
8
9
10
11
12
13
14
15from dataclasses import dataclass
@dataclass()
class X:
a:int
b:int
range:int
def __call__(self):
print('__call__ with ({}, {})'.format(self.a, self.b))
x = X(1,2,3)
print(x)
x() # 把实例直接当函数调用