访问属性时,发送到另一个实例

2024-04-24 09:56:16 发布

您现在位置:Python中文网/ 问答频道 /正文

class x():
    def __init__(self):
        self.z=2

class hi():
    def __init__(self):
        self.child=x()

f=hi()
print f.z

我想把它打印出来。你知道吗

基本上我想把对那个类的调用转发到另一个类。你知道吗


Tags: selfchildinitdefhiclassprint
2条回答

最简单的方法是实现^{}

class hi():
    def __init__(self):
        self.child=x()

    def __getattr__(self, attr):
        return getattr(self.child, attr)

这有一定的缺点,但它可能适用于您有限的用例。您可能还需要实现__hasattr____setattr__。你知道吗

Python语法是:

class hi(x):

hiinherit(应该是x的子级。你知道吗

是的。你知道吗

注意:为了使hi具有属性z(因为这是在hi__init__x.__init__需要在x中显式运行。也就是说,

class hi(x):
    def __init__(self):
        x.__init__(self)

相关问题 更多 >