python 面向对象(类的特殊成员)

时间:2023-03-08 22:51:51
python 面向对象(类的特殊成员)

python 面向对象:

(思维导图 ↑↑↑↑)

类的特殊成员

  python的类成员存在着一些具有特殊含义的成员

1.__init__: 类名() 自动执行 __init__

class Foo(object):

    def __init__(self,a1,a2):
self.a1 = a1
self.a2 = a2 obj = Foo(1,2)

2.__call__: 对象() 自动执行__call__

class Foo(object):

    def __call__(self, *args, **kwargs):
print(1111,args,kwargs)
return 123 obj = Foo()
ret = obj(6,4,2,k1=456)

3.__getitem__: 对象['xx'] 自动执行__getitem__

class Foo(object):

    def __getitem__(self, item):
print(item)
return 8
obj = Foo()
ret = obj['yu']
print(ret)

4.__setitem__: 对象['xx'] = 11 自动执行__setitem__

class Foo(object):

    def __setitem__(self, key, value):
print(key, value, 111111111)
obj = Foo()
obj['k1'] = 123

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

class Foo(object):

    def __delitem__(self, key):
print(key)
obj = Foo()
del obj['uuu']

6.__add__: 对象+对象 自动执行__add__

class Foo(object):
def __init__(self, a1, a2):
self.a1 = a1
self.a2 = a2
def __add__(self,other):
return self.a1 + other.a2
obj1 = Foo(1,2)
obj2 = Foo(88,99)
ret = obj2 + obj1
print(ret)

7.__enter__ / __exit__: with 对象 自动执行__enter__ / __exit__

class Foo(object):
def __init__(self, a1, a2):
self.a1 = a1
self.a2 = a2
def __enter__(self):
print('')
return 999 def __exit__(self, exc_type, exc_val, exc_tb):
print('')
obj = Foo(1,2)
with obj as f:
print(f)
print('内部代码')

8.__new__: 构造方法

class Foo(object):
def __init__(self, a1, a2): # 初始化方法
"""
为空对象进行数据初始化
:param a1:
:param a2:
"""
self.a1 = a1
self.a2 = a2 def __new__(cls, *args, **kwargs): # 构造方法
"""
创建一个空对象
:param args:
:param kwargs:
:return:
"""
return object.__new__(cls) # Python内部创建一个当前类的对象(初创时内部是空的.). obj1 = Foo(1,2)
print(obj1) obj2 = Foo(11,12)
print(obj2)