【问题标题】:Call a method in an outer object from an inner object从内部对象调用外部对象中的方法
【发布时间】:2022-01-10 23:36:16
【问题描述】:

A 类将 B 类中的对象实例化为成员变量。这个 B 类对象如何从 A 类对象调用方法?当我执行下面的程序时,我希望打印一个“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 object


    【解决方案1】:

    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 行。在 Python 中,您不需要像在 Java 或 C++ 中那样在类的顶部声明实例变量。相反,您只需使用self. 分配给它们,它们就会开始存在。 other = None 在该范围内创建了一个类变量,类似于Java 中的静态变量,可以被A.other 引用(注意大写A;这是类本身,而不是实例)。

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

    【讨论】:

    • 非常好的答案,非常感谢!很有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 2019-10-22
    • 2010-09-26
    • 2010-12-21
    相关资源
    最近更新 更多