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上)。
发布于 2018-06-21 17:22:25
定义一个__getattr__
class Qux(Foo):
def __init__(self):
self.item = Foo()
def __getattr__(self, attr):
return getattr(self.item, attr)每当有人试图查找对象的属性时,__getattr__就会被调用,但通过正常方法失败。
它有一个名为__getattribute__的邪恶孪生体,它总是被调用,并且必须非常谨慎地使用。
发布于 2018-06-21 17:23:52
您可以通过定义__getattr__来实现这一点,而不是使用属性。对于标准协议无法找到的任何属性,Python将调用类的__getattr__方法。
此外,要存储item,必须将其分配给self.item,否则将在Qux.__init__末尾抛出它。
最后,在这种情况下,从Foo继承似乎是没有必要的。
class Foo:
def __init__(self, superpower):
self.superpower = superpower
class Qux:
def __init__(self, foo_item):
self.item = foo_item
def __getattr__(self, name):
return getattr(self.item, name)示例
f = Foo('strenght')
q = Qux(f)
print(q.superpower) # 'strenght'继承
虽然,您似乎已经尝试过用继承来实现这一点。如果您的目的是用Qux扩展Foo行为,那么继承就是最好的选择。
class Foo:
def __init__(self, superpower):
self.superpower = superpower
class Qux(Foo):
def __getattr__(self, name):
return getattr(self.item, name)示例
q = Qux('strenght')
print(q.superpower) # 'strenght'https://stackoverflow.com/questions/50974265
复制相似问题