python可以自定义属性的操作
__setattr__()
如果类定义了该方法,那么对实例设置属性时实例.属性=值,python会自动调用__setattr__()方法
#coding=utf-8
class Phone:
def __setattr__(self,name,value):
print("设置属性:%s=%s"%(name,value))
self.__dict__[name] = value
huawei=Phone()
huawei.name="华为p10"
huawei.name="华为p20"
print(huawei.name)
总结:
在
__setattr__()方法内,不能执行self.属性=值,因为会再次调用__setattr__()方法,即导致死循环给实例添加属性,其实就是给实例的
__dict__内置属性设置key-value
参见链接:
http://www.malaoshi.top/show_1EF2CdO4Y648.html
__getatrribute__()
在访问对象的属性时,一定会调用__getattribute__()方法
注意:
在该方法内,不能执行self.属性,因为会再次调用__getatrribute__()方法,即导致死循环
#coding=utf-8
class Phone:
def __getattribute__(self,name):
print("调用__getattribute__方法,name=%s"%name)
#不要调用下面代码,会死循环
# return self.__dict__[name]
#通过object类的__getattribute__()方法实现功能
return object.__getattribute__(self,name)
huawei=Phone()
huawei.rom="64G"
#调用实例的__dict__属性时,也会调用__getattribute__()方法
print("huawei.__dict__是===",huawei.__dict__)
#访问实例的属性时,会调用__getattribute__()方法
print(huawei.rom)
__getattr__()
访问对象的属性时,当该属性不在对象的__dict__属性中,python会调用__getattr__()方法。
参见代码(不会调用__getattr__()方法):
#coding=utf-8
class Phone:
def __getattr__(self,name):
print("调用getattr方法,name=%s"%name)
return self.__dict__[name]
huawei=Phone()
huawei.name="华为p10"
print("huawei.__dict__是===",huawei.__dict__)
#由于name属性在huawei.__dict__中,所以不会调用__getattr__()方法
print(huawei.name)
参见代码(调用__getattr__()方法):
#coding=utf-8
class Phone:
def __getattr__(self,name):
print("调用getattr方法,name=%s"%name)
return None
huawei=Phone()
print("huawei.__dict__是===",huawei.__dict__)
#由于cpu属性不在huawei.__dict__中,所以会调用__getattr__()方法
print(huawei.cpu)
注意:
在__getattr__()方法内,不能执行self.属性,因为会再次调用__getattr__()方法,即导致死循环
__delattr__()
使用del删除实例的属性时,会调用__delattr__()方法
#coding=utf-8
class Phone:
def __delattr__(self,name):
print("调用delattr方法,name=%s"%name)
del self.__dict__[item]
huawei=Phone()
print("huawei.__dict__是===",huawei.__dict__)
#使用del关键字时,会调用__delattr__()方法
del huawei.cpu
print("huawei.__dict__是===",huawei.__dict__)