面向对象的特殊语法,特殊方法
1.python 中 通过类来创建对象,实际上先通过__new__放法返回 一个空对象 ,__init__方法来初始化数据
# class Foo: # def __init__(self,name): # self.name = name # def __new__(cls, *args, **kwargs): # ''' # # :param args: 任意位置参数 # :param kwargs: 任意关键字参数 # :return: 返回空 # ''' # print('__new__执行') # return # obj = Foo('cat') # print(obj.name) #AttributeError: 'NoneType' object has no attribute 'name' 调用obj.name 报错
class Foo: def __init__(self,name): ''' python __init__方法 初始化对象中的数据 :param name: ''' self.name = name def __new__(cls, *args, **kwargs): ''' 严格意义上的构造方法 :param args: 任意位置参数 :param kwargs: 任意关键字参数 :return: 返回空对象 ''' print('__new__执行') return object.__new__(cls) obj = Foo('cat') print(obj.name)
2.对象() 实际上调用了类中的__call__(self,**args,**kwargs) 方法,有返回值
class Foo: def __init__(self,name): self.name = name def __call__(self, *args, **kwargs): print(args,kwargs) return 1 obj = Foo('cat') ret = obj(1,2,3,ky = '123'}) print(ret)
结果:
(1 2 3) {'ky': '123'}
1
3. 对象['xx'] 调用了 __getitem__(self,item)放法,有返回值
class Foo: def __init__(self,name): self.name = name def __getitem__(self, item): print('__item__') return 1 obj = Foo(1) ret = obj['a'] print(ret)
4 对象['xx'] ==cc 调用了 __setitem(sef,k,v)方法,没返回值
class Foo: def __init__(self,name): self.name = name def __setitem__(self, key, value): print('__setitem__') obj = Foo(1) ret = obj['a']='b' #这里相当于给ret赋值 print(ret)
5.obj1 + obj2 对象加对象 调用了 __add__(self,other)方法,有返回值 那个对象在前边self就是那个
class Foo: def __init__(self,a1,b1): self.a1 = a1 self.b1 = b1 def __add__(self, other): return self.a1 +self.b1 obj = Foo(1,2) obj1 = Foo(11,22) ret = obj + obj1 print(ret)
6.with 开始调用 __enter__(self), 结束调用__exit__ 好多参数
class Foo: def __enter__(self): print('haha') return 2 def __exit__(self, exc_type, exc_val, exc_tb): print('不高兴') obj = Foo() with obj as f: print(f) print('高兴起来')
#这里的执行顺序 先执行 __enter__方法 ,再执行 whith obj:里边的东西,最后执行__exit__函数
7.del 调用 __del__ (self)方法
class Foo: def __del__(self): print('del') obj = Foo() del obj
8.__str__(self) 这个方法相当于给对象重新起名字
class Foo: def __init__(self,name): self.name =name def __str__(self): return 'f1' obj = Foo('hah') print(obj)
#f1
9.__doc__ 查看类的注释
10.__dict__ 查看对象中封装的数据
class Foo: def __init__(self,name,age): self.name =name self.age =age obj = Foo('ting','32') print(obj.__dict__) #这里以字典形式展示
#{'age': '32', 'name': 'ting'}
11.__iter__ 1.添加__iter__方法 ,返回迭代器或者生成器(也是一种特殊的迭代器),把不可迭代的对象变成可迭代的
class Foo: def __init__(self,name,age): self.name =name self.age =age def __iter__(self): return iter([11,12,13]) obj = Foo('ting','32') for item in obj: print(item)

浙公网安备 33010602011771号