class Foo(object):
def __init__(self, value):
self.value = value
def __getattr__(self, item):
print item # 查看得到的参数是什么
print type(item) # 参数的类型是什么
return 'attr:%s' % item # 最后返回一个东西看其行为如何
a = Foo('scolia') # 创建一个实例
print a.value print type(a.value)
print a.abc
class Foo(object):
def __init__(self, value):
self.value = value
def __getattr__(self, item):
if item == 'scolia':
return 'can not set attr: %s' % item # 访问不存在的scolia属性时,打印一句话而不报错
else:
raise AttributeError('not attr name: %s' % item) # 访问其他不存在的属性时,触发异常。
a = Foo(123) print a.value # 访问存在的属性
print a.scolia # 访问不存在的属性,但我们做了特殊处理的
print a.good # 访问不存在的属性,但应该触发异常的
a.scolia = 321 print a.scolia
class Foo(object):
def __init__(self, value, defulat=None):
self.value = value
self.__defulat = defulat
def __getattr__(self, item):
item = item.lower() # 用字符串的方法对其进行小写
if item in self.__dict__:
return self.__dict__[item] # 返回相应的属性
else:
self.__dict__[item] = self.__defulat # 若属性不存在则添加这个属性并使用默认值
return self.__dict__[item]
a = Foo(123)
a.scolia = 321
print a.SCOlia
print a.good
class Foo(object):
def __init__(self, value, defulat=None):
self.value = value
def __setattr__(self, key, value):
print key, type(key)
print value, type(value)
a = Foo('scolia')
b = Foo(123)
print a.value
class Foo(object):
def __init__(self, value):
self.value = value
def __getattribute__(self, item):
return self.__dict__[item]
a = Foo('scolia')
print a.value
class Foo(object):
def __init__(self, value):
self.value = value
def __getattribute__(self, item):
return object.__getattribute__(self, item) # 非绑定方法要显式传递self
a = Foo('scolia')
print a.value
class Boo(Foo):
def __init__(self, value):
self.value = value
def __getattribute__(self, item):
return Foo.__getattribute__(self, item)
# return super(Boo, self).__getattribute__(item) 也可以使用super函数让python自动在其父类们寻找这个方法。
a = Foo('scolia')
print a.value
b = Boo(123)
print b.value
class Foo(object):
def __init__(self, value):
self.value = value
def __getattr__(self, item):
if item == 'scolia':
return 'no attr:%s' % item
elif item in self.__dict__:
return self.__dict__[item]
else:
raise AttributeError('no attr:%s' % item)
def __setattr__(self, key, value):
if key == 'good':
print 'can not set the attr: good'
else:
self.__dict__[key] = value
def __delattr__(self, item):
if item == 'a':
print 'no attr: good'
else:
del self.__dict__[item]
def __getattribute__(self, item):
if item == 'a':
raise AttributeError('not a')
return object.__getattribute__(self, item)
a = Foo('scolia')
print a.value # 正常访问
a.a = 123 # __getattribute__会触发AttributeError异常,此时调用__getattr__
# 而__getattr__添加了这个属性,所以最后异常没有触发,属性也添加了
print a.a # 结果能够访问
del a.a # 试图删除这个属性
print a.a # 删除行为被阻止了,所以该属性还在
a.good = 'good' # 因为添加被阻止了
print a.good # 所以访问失败了
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有