主动调用其他类的方法 类名.方法(self) 与继承无关 手动填写self
super().f1() 按顺序去父类里找f1函数
特殊成员
1.类名() 自动执行__init__
obj = Foo(1,2)
2.对象() 自动执行__call__ (需要在__call__方法里写方法)
ret = obj(6,4,2,k1=456)
3.对象[‘xx’] 自动执行__getitem__ (需要在__getitem__方法里写方法)
ret = obj[‘xx’]
4.对象[‘xx’] = 123 自动执行__setitem__ (需要在__setitem__方法里写方法)
obj[‘xx’] = 123
5.del 对象[‘xx’] 自动执行__delitem__ (需要在__del__方法里写方法)
del obj[‘xx’]
6.对象+对象 自动执行__add__
obj1 = Foo(1,2)
obj2 = Foo(88,99)
ret = obj1 + obj2 (需要在__add__方法里写方法)
7.with 对象: 自动执行__enter__和__exit__ with 对象 as f: 自动执行__enter__ / exit 返回enter的return
obj = Foo(1,2)
with obj as f:
print(f)
print(‘内部代码’)
还有好多此处不列举等等等等…
8.真正的构造方法 类名() 先执行__new__方法 (有返回值返回创建当前类) 再 执行 __init__方法
class Foo(object):
def init(self, a1, a2):
“”"
为空对象进行数据初始化
:param a1:
:param a2:
“”"
print(1)
self.a1 = a1
self.a2 = a2
def __new__(cls, *args, **kwargs):
"""
创建一个空对象
:param args:
:param kwargs:
"""
print(2)
return object.__new__(cls) # python 内部创建一个当前类的对象(初创时内部是空的)
obj = Foo(1, 2)
打印结果是2 1
dict
class Foo:
def init(self,name,age):
self.name = name
self.age = age
obj = Foo(‘zhang’,‘16’)
print(obj.dict)
打印结果{‘name’: ‘zhang’, ‘age’: ‘16’}
iter
class Foo:
def init(self, name, age):
self.name = name
self.age = age
def __iter__(self):
return iter([self.name, self.age])
obj = Foo(‘name’, ‘age’)
for item in obj:
print(item)
打印结果
name
age