Python で他のクラスのメソッドを呼び出す方法
他のクラスのメソッドを呼び出すには、そのクラスのインスタンスオブジェクトを作成してから、インスタンスオブジェクトを通して該当するメソッドを呼び出します。以下にサンプルコードを示します。
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 中的方法
上記の例では、MyClassとAnotherClassの2つのクラスを作成し、AnotherClassのanother_methodメソッド内でMyClassのインスタンスオブジェクトmy_objを作成し、my_obj.my_method()を介してMyClassのmy_methodメソッドを呼び出しました。最後に、メインプログラムでAnotherClassのインスタンスオブジェクトanother_objを作成し、another_obj.another_method()を介してAnotherClassのanother_methodメソッドを呼び出しました。以上を実行すると、次の出力が得られます。
调用了 AnotherClass 中的方法
调用了 MyClass 中的方法