在子实例中调用父实例的方法

2024-05-14 18:21:11 发布

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

让子类(B)实例调用其父类(a)实例的某个方法的最佳方法是什么?将self传递到子类(B)的实例中似乎是可行的,但不知何故,这似乎并不是一种有效或良好的做法。有更好的办法吗?在

class A():
    def __init__(self,name):
        self.instanceOfB = self.B(self)
        self.name = name

    def hello(self):
        print 'Hello '+self.name

    class B():
        def __init__(self,parent):
            self.parent = parent

        def hi(self):
            self.parent.hello() ##Call parent instance's method 'hello()' here

instanceOfA = A('Bob')
instanceOfA.instanceOfB.hi()

应导致:

^{pr2}$

@classmethod和{}只有在A.hello()不依赖于用类A实例化的任何信息时才有效


Tags: 实例方法nameselfhelloinitdefhi

热门问题