__getattr__和__setattt__使用】的更多相关文章

# coding:utf-8 """ __setattr__(self, name, value),如果要给name赋值,调用此方法 __getattr__(self, name) 如果name被访问,同时它不存在的时候,此方法被调用 __getattribute__(self, name) 当name被访问时自动被调用(这个进用于新类式),无论name是否存在,都要被调用 __delattr__(self, name) 如果要删除name,这个方法就被调用 "&q…
代码: #!/usr/bin/env python #! -*- coding:utf-8 -*- class A(object): def __setattr__(self, key, value): self.__dict__[key] = value def __getattr__(self, name): return "xxx" obj = A() 执行操作的代码: 代码1: print(obj.__dict__) 结果: {} # 空字典 代码2: print(obj.na…
class Foo: def __init__(self,x): self.x=x def __getattr__(self, item): print("执行的是我----->") def __getattribute__(self, item): print('不管是否纯在,我都执行-------->') raise AttributeError("接口") f1 = Foo(10) f1.x f1.xxxxxxxxxxxx…
27. 属性的__dict__系统 1)对象的属性可能来自: 其类的定义,叫做类属性 继承父类的定义 该对象实例定义(初始化对象时赋值),叫做对象属性 2)对象的属性存储在对象的 __dict__ 属性中: __dict__ 为字典,键为属性名,值是属性本身. 例子: class bird(object): feather = True # 父类 class chicken(bird): fly = False def __init__(self, age): self.age = age #…
直接上代码 >>> class Test(object): ... def __getattr__(self,attr_name): ... setattr(self, attr_name, '(default)') ... return self.attr_name ... >>> t=Test() >>> t.name '(default)' >>> t.age '(default)' >>> t.name='s…
1. ConfigParser format.conf [DEFAULT] conn_str = %(dbn)s://%(user)s:%(pw)s@%(host)s:%(port)s/%(db)s dbn = mysql user = root host = localhost port = 3306 [db1] user = aaa pw = ppp db = example [db2] host = 172.16.88.1 pw = www db = example readformati…
python __setattr__, __getattr__, __delattr__, __call__ getattr `getattr`函数属于内建函数,可以通过函数名称获取 value = obj.attribute value = getattr(obj, "attribute") 使用`getattr`来实现工厂模式 #一个模块支持html.text.xml等格式的打印,根据传入的formate参数的不同,调用不同的函数实现几种格式的输出 import statsout…
访问顺序: 实例的__getattribute__().Descriptor的__get__().实例的__dict__.只读Descriptor的__get__().实例的__getattr__(): 实例的__setattr__().Descriptor的__set__().实例的__dict__: 实例的__delattr__().Descriptor的__delete__().实例的__dict__.…
一:最基本的属性操作 class Generic: pass g= Generic() >>> g.attribute= "value" #创建属性并赋值 >>> g.attribute 'value' >>> g.unset Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeEr…
在之前的文章有提到__getattr__函数的作用: 如果属性查找(attribute lookup)在实例以及对应的类中(通过__dict__)失败, 那么会调用到类的__getattr__函数, 如果没有定义这个函数,那么抛出AttributeError异常.由此可见,__getattr__一定是作用于属性查找的最后一步,兜底. 我们来看几个例子:   第一个例子,很简单但经典,可以像访问属性一样访问dict中的键值对. class ObjectDict(dict): def __init_…