动态公开对象属性

维沙尔
In [1]: class Foo():
   ...:     pass
   ...: 

In [2]: class Qux():
   ...:     def __init__(self):
   ...:         item = Foo()
   ...:         

In [3]: a = Foo()

In [4]: setattr(a, 'superpower', 'strength')

In [5]: a.superpower
Out[5]: 'strength'

In [6]: b = Qux()

In [7]: b.item = a

In [8]: b.superpower
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-cf0e287006f1> in <module>()
----> 1 b.superpower

AttributeError: Qux instance has no attribute 'superpower'

我想定义一种在Qux上调用任何属性并使它返回的方法getattr(Qux.item, <attributename>)换句话说,在没有明确定义的情况下进行b.superpower工作

@property
def superpower(self):
    return getattr(self.item, 'superpower')

我也不想失去对Qux自身定义的任何属性的访问,而是要公开定义在上的属性(Foo如果它们也未启用)Qux

L3viathan

定义一个__getattr__

class Qux(Foo):
    def __init__(self):
        self.item = Foo()
    def __getattr__(self, attr):
        return getattr(self.item, attr)

__getattr__ 每当有人尝试查找对象的属性时都会被调用,但通过常规方法失败。

它有一个邪恶的孪生子,称为__getattribute__总是被调用,必须非常谨慎地使用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章