温馨提示×

python如何调用其他类中的方法

小亿
106
2023-11-02 01:00:58
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要调用其他类中的方法,需要先创建该类的实例对象,然后通过实例对象调用相应的方法。以下是一种示例代码:

class MyClass:
    def my_method(self):
        print("调用了 MyClass 中的方法")

class AnotherClass:
    def another_method(self):
        print("调用了 AnotherClass 中的方法")
        my_obj = MyClass()  # 创建 MyClass 的实例对象
        my_obj.my_method()  # 调用 MyClass 中的方法

another_obj = AnotherClass()  # 创建 AnotherClass 的实例对象
another_obj.another_method()  # 调用 AnotherClass 中的方法

在上面的示例中,我们创建了两个类 MyClassAnotherClassAnotherClass 中的 another_method 方法中创建了 MyClass 的实例对象 my_obj,然后通过 my_obj.my_method() 调用了 MyClass 中的 my_method 方法。最后,在主程序中创建了 AnotherClass 的实例对象 another_obj,并通过 another_obj.another_method() 调用了 AnotherClass 中的 another_method 方法。运行以上代码,会输出以下结果:

调用了 AnotherClass 中的方法
调用了 MyClass 中的方法

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python怎么调用其他类中的方法

0