繁体   English   中英

从内部 object 调用外部 object 中的方法

[英]Call a method in an outer object from an inner object

Class A 将 Class B 中的 object 实例化为成员变量。 这个 class B object 如何从 Class A object 调用方法? 当我执行下面的程序时,我希望打印一个“Hello”,但我收到一个错误,而不是说“name 'a' is not defined”

这里有什么问题,我该如何解决?

class B:
    def __init__(self):
        a.say_hello()

class A:
    other = None

    def __init__(self):
        self.other = B()

    def say_hello():
        print("Helo")

a = A()

Python 引用是单向的。 您需要保留反向的引用才能使其正常工作。

class B:
    def __init__(self, outer):
        outer.say_hello()

class A:
    # other = None # (see below)

    def __init__(self):
        self.other = B(self)

    def say_hello():
        print("Helo")

a = A()

如果您需要的outer构造函数,您可以将其存储在实例变量中。

您也不需要other = None行。 In Python, you don't need to declare your instance variables at the top of the class like you do in Java or C++. 相反,您只需使用self. 分配给他们,他们开始存在。 other = None in that scope makes a class variable , similar to static variable in Java, that can be referenced by A.other (Note the capital A ; this is the class itself, not an instance of it).

在某些情况下,您可能希望以某种形式在 class 的顶部声明实例变量( __slots__和 PEP 484 注释是主要的两个),但是对于刚开始的简单类,没有必要,并且像这样的任务不会达到你的预期。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM