我在Python中有以下代码示例:
class Parent():
def methodA(self):
return self.methodB()
def methodB(self):
print("I am a parent")
class Child():
def __init__(self, parent):
self.parent = parent
def __getattr__(self, name):
try:
return getattr(self.parent, name)
except AttributeError:
raise AttributeError(f"'{__class__.__name__}' object has no attribute '{name}'")
def methodB(self):
print("I am a child")
parent = Parent()
child = Child(parent)
child.methodA()
# Output: "I am a parent"
# Desired output: "I am a child"
我希望Parent的methodA调用Child的methodB,以便输出为“我是孩子”。 有没有不使用继承的方法?