关于类里的一些特殊成员

类里的一些特殊成员

 1 class Foo(object):
 2 
 3     def __init__(self,a1,a2):
 4         self.a1 = a1
 5         self.a2 = a2
 6     
 7     def __call__(self, *args, **kwargs):
 8         print(11111,args,kwargs)
 9         return 123
10 
11     def __getitem__(self, item):
12         print(item)
13         return 8
14 
15     def __setitem__(self, key, value):
16         print(key,value,111111111)
17 
18     def __delitem__(self, key):
19         print(key)
20 
21     def __add__(self, other):
22         return self.a1 + other.a2
23 
24     def __enter__(self):
25         print('1111')
26         return 999
27 
28     def __exit__(self, exc_type, exc_val, exc_tb):
29         print('22222')

关于特殊方法的执行方式
1、类名 ()  自动执行 __init__

2、对象 ()  自动执行 __call__ 有返回值

 ret=obj(6,4,2,k1=478)

3、对象["xx"]  自动执行 __getitem__ 有返回值

ret=obj["mm"]

print(ret)

4、对象["xx"] =124 自动执行 __setitem__

obj['k1'] = 123  # "k1" 给key 传值,123给value传值

5、del 对象[xx]       自动执行__delitem__

del obj["xxx"]

6、对象+对象      自动执行__add__

obj1=Foo(1,2) 参数分别传给self other

obj2=Foo(3,4)

ret=obj1+obj2

7、with 对象        自动执行 __enter__ / __exit__ 按顺序执行

with obj as f:
     print(f)
     print('内部代码')

#1111
#999
#内部代码
#22222

8、真正的构造方法

 1 class Foo(object):
 2     def __init__(self, a1, a2):     # 初始化方法
 3         """
 4         为空对象进行数据初始化
 5         :param a1:
 6         :param a2:
 7         """
 8         self.a1 = a1
 9         self.a2 = a2
10 
11     def __new__(cls, *args, **kwargs): # 构造方法
12         """
13         创建一个空对象
14         :param args:
15         :param kwargs:
16         :return:
17         """
18         return object.__new__(cls) # Python内部创建一个当前类的对象(初创时内部是空的.).
19 
20 obj1 = Foo(1,2)
21 print(obj1)
22 
23 obj2 = Foo(11,12)
24 print(obj2)
原文地址:https://www.cnblogs.com/liaopeng123/p/9555243.html