一、几个常见的特殊成员
# 都只是语法,无特殊意义 class Foo(object): def __init__(self,a1,a2): self.a1 = a1 self.a2 = a2 def __call__(self,*args,**kwargs): print(11111,args,kwargs) return 123 def __getitem__(self, item): print(item) return 8 def __setitem__(self, key, value): print(key,value,111111111) def __delitem__(self, key): print(key) def __add__(self, other): return self.a1+ other.a2 def __enter__(self): print('111') return 999 def __exit__(self, exc_type, exc_val, exc_tb): print('222') # 1.类名() 自动执行 __init__ obj = Foo(1,2) # 2.对象() 自动执行 __call__ res=obj(6,4,2,k1=456) print(res) print("#"*20) # 3.对象[] 自动执行 __getitem__ ret= obj['yu'] print(ret) print("#"*20) # 4.对象['xx']=11 自动执行 __setitem__ obj['k1'] = 123 print("#"*20) # 5.del 对象[xx] 自动执行 __delitem__ del obj['aaa'] print("#"*20) # 6.对象+对象 自动执行 __add__ obj1 = Foo(1,2) obj2 = Foo(88,99) ret=obj2+obj1 print(ret) print("#"*20) # 7.with 对象 自动执行 __enter__ / __exit__ with obj as f: print(f) print('内部代码')
# 8.真正的构造方法 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) v1=object.__new__(cls) # Python内部创建一个当前类的象(初创时内部是空的.) print(v1) return v1 obj = Foo(1,2) print(obj)
二、特殊成员的补充
1、__str__
__doc__
代码:
class Foo(object): """ Foo类 """ def __init__(self): pass def func(self): pass def __str__(self): # __str__(self) return "F1" obj = Foo() print(obj,type(obj)) print(obj.__doc__) # __doc__
结果:
2、__dict__
class Foo(object): def __init__(self,name,age): self.name = name self.age = age def func(self): pass obj1 = Foo("lin",99) obj2 = Foo("yang",89) print(obj1.__dict__) # {'name': 'lin', 'age': 99} print(obj2.__dict__) # {'name': 'yang', 'age': 89}
3、 __iter__
#l1是list类的一个对象,可迭代对象 l1 = [11,22,33,44] l1 = [11,22,33,44] class Foo(object): def __init__(self,name,age): self.name = name self.age = age def func(self): pass def __iter__(self): # return iter([11,22,33,44]) yield 11 yield 22 yield 33 # obj1是Foo类的一个对象,不可迭代对象 # 如果想要把不可迭代対象 → 可迭代对象 # 1.在类中定义 __iter__ 方法 # 2.iter内部返回一个迭代器(生成器也是一种特殊迭代器) obj1 = Foo("lin",99) for item in obj1: print(item)