温馨提示×

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

小亿
81
2023-11-02 01:00:58
栏目: 编程语言

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

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 中的方法

0