python常用的魔法函数简单运用
1、创建一个.py的文件~




2、比较常用的魔法方法比如有:
__new__
__init__
__str__
__del__
__call__
__setattr__
__getattr__
__enter__
__exit__ ...等等

3、__new__与__init__
__new__在实例创建之前被调用的,就是创建实例后返回该实例对象,是个静态方法。
__init__是当实例对象创建完成后被调用的,然后设置对象属性的一些初始值,通常用在初始化一个类实例的时候。是一个实例方法。
class Foo(object): def __init__(self): print('init') def __new__(cls, *args, **kwargs): print('new') return object.__new__(cls) #__new__ 没有返回实例对象,则__init__ 不会被调用。

4、常利用与开发模式:单例
确保一个类只有一个实例
应用场景:
client--->访问AppConfig()类读取配置文件信息
很多地方同时调用就会实例多个浪费server资源
单例模式就可以解决!
class Singleton(object): __instance=None def __new__(cls, *args, **kwargs): if cls.__instance is None: cls.__instance=object.__new__(cls) return cls.__instance

5、初始化类属性时,私有化属性只能类自身调用
class Foo(object): def __init__(self,x,y): self.x=x self.__y=yf=Foo(1,2)# print(f.x,f.y) 不能直接调用私有化属性

6、对私有化属性取值和设置有2种方法
方法1:
class Foo(object): def __init__(self,x,y): self.x=x self.__y=y def __new__(cls, *args, **kwargs): print('new') return object.__new__(cls) def getY(self): return self.__y def setY(self,y): self.__y=yf=Foo(1,2)f.x=3f.setY(4)print(f.x,f.getY())
方法2:
class Foo(object): def __init__(self,x,y): self.x=x self.__y=y def __new__(cls, *args, **kwargs): print('new') return object.__new__(cls) @property def y(self): return self.__y @y.setter def y(self,y): self.__y=yf=Foo(1,2)f.x=3f.y=4print(f.x,f.y)


7、__str__
返回一个字符串,当做这个对象的描写
当调用print时打印使用
class Foo: def __str__(self): return 'describe'f=Foo()print(f)

8、__call__
将类的对象当作函数直接调用
class Foo: def __call__(self, *args, **kwargs): print('call method')f=Foo()f()

9、__enter__和__exit__
这2个方法一般我们会想到使用
with open('1.txt','r') as f:
这样的方法。其实它的实现就是基于这2个魔法函数
class Foo: def open(self): print('open') def do(self): print('do') def close(self): print('close') def __enter__(self): self.open() def __exit__(self, exc_type, exc_val, exc_tb): self.close()f=Foo()with f: f.do()

10、__getattr__和__setattr__
__getattr__访问一个不存在的属性时会调用此方法,如果属性存在则不会调用。
__setattr__所有的属性设置都会调用此方法,并且只有拥有这个魔法方法的对象才可以设置属性
class Foo: def __init__(self,x): self.x=x def __getattr__(self, item): return item def __setattr__(self, key, value): print('set') object.__setattr__(self, key, value)f=Foo(3)f.x=4print(f.x)print(f.y)

11、还有其他一些不太常用
__add__
class Foo:
def __init__(self,x):
self.x=x
def __add__(self, other):
return self.x+other.x
f1=Foo(3)
f2=Foo(4)
print(f1+f2)
