python 面向对象的一些魔法方法和反射
1.with和__enter__,__exit__,__init__配合使用
class A:
def __init__(self):
print('init')
def __enter__(self):
print('before')
def __exit__(self, exc_type, exc_val, exc_tb):
print('after')
def __new__(cls, *args, **kwargs):
print('in new function')
return object.__new__(A)
with A() as a:
print('123')
结果:in new function,init,before,123,after
2.__del__ 析构方法,当对象在内存中被释放时,自动触发执行
3.__str__和__repr__ 改变对象的字符串显示__str__,__repr__
class B:
def __str__(self):
return 'str : class B'
def __repr__(self):
return 'repr : class B'
b = B()
print('%s' % b)
print('%r' % b)
4.对象的四个可以实现自省的函数hasattr,getattr,setattr,delattr
class Foo:
f = '类的静态变量'
def __init__(self,name,age):
self.name=name
self.age=age
def say_hi(self):
print('hi,%s'%self.name)
obj=Foo('egon',73)
#检测是否含有某属性
print(hasattr(obj,'name'))
print(hasattr(obj,'say_hi'))
#获取属性
n=getattr(obj,'name')
print(n)
func=getattr(obj,'say_hi')
func()
print(getattr(obj,'aaaaaaaa','不存在啊')) #报错
#设置属性
setattr(obj,'sb',True)
setattr(obj,'show_name',lambda self:self.name+'sb')
print(obj.__dict__)
print(obj.show_name(obj))
#删除属性
delattr(obj,'age')
delattr(obj,'show_name')
delattr(obj,'show_name111')#不存在,则报错