class互相调用方法
时间: 2023-08-15 09:13:26 浏览: 55
在类中,可以通过创建对象并使用对象来调用其他类的方法。下面是一个示例代码:
```python
class A:
def method1(self):
print("This is method1 of class A")
def method2(self, obj_B):
print("This is method2 of class A")
obj_B.method3()
class B:
def method3(self):
print("This is method3 of class B")
def method4(self, obj_A):
print("This is method4 of class B")
obj_A.method1()
# 创建对象
obj_A = A()
obj_B = B()
# 调用方法
obj_A.method2(obj_B) # 调用 A 类的 method2 方法,传递 obj_B 对象作为参数
obj_B.method4(obj_A) # 调用 B 类的 method4 方法,传递 obj_A 对象作为参数
```
在上面的示例中,类 `A` 中的 `method2` 方法调用了类 `B` 中的 `method3` 方法,而类 `B` 中的 `method4` 方法调用了类 `A` 中的 `method1` 方法。通过使用对象来调用其他类的方法,实现了类之间的相互调用。