You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从下方Second类调用上方First类的method_2方法

解决方案:在Second类中调用First类的method_2方法

当前代码运行会抛出NameError,因为Second类的method_1中引用的first是main函数的局部变量,不在Second的作用域内。要实现需求,关键是让Second类能获取到First类的实例对象,以下是两种可行的实现方式:

方法一:创建Second实例时传入First实例

通过在初始化Second时传递First的实例,让Second持有该引用,后续即可调用其方法:

class First():
    def method_1(self):
        print("First method_1 runed")
        # 传入当前First实例给Second
        self.second = Second(self)
        self.second.method_1()

    def method_2(self):
        print("First - method_2 runed")

class Second():
    def __init__(self, first_instance):
        # 保存First实例引用
        self.first = first_instance

    def method_1(self):
        # 通过引用调用First的method_2
        self.first.method_2()

def main():
    first = First()
    first.method_1()

if __name__ == "__main__":
        main()

方法二:调用Second的method_1时传入First实例

如果不需要在Second实例中长期持有First引用,可以在调用method_1时临时传入:

class First():
    def method_1(self):
        print("First method_1 runed")
        self.second = Second()
        # 调用method_1时传入当前First实例
        self.second.method_1(self)

    def method_2(self):
        print("First - method_2 runed")

class Second():
    def method_1(self, first_instance):
        first_instance.method_2()

def main():
    first = First()
    first.method_1()

if __name__ == "__main__":
        main()

注意事项

  • 这两种方式本质都是让Second获取到First的实例对象,因为method_2是实例方法,必须通过实例调用。
  • 双向引用场景下如果涉及大量对象,需注意内存回收问题,Python的垃圾回收机制会处理大部分情况,但复杂场景可考虑使用弱引用(weakref模块)避免循环引用无法回收。

内容的提问来源于stack exchange,提问作者Stano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 15:13:15