从父类实例创建子类实例,并从子类实例调用父方法



我希望我能做两件事:

    1. 从父类的实例创建尽可能多的子类(我能做什么)
    1. 从 Child 类的实例调用父类的方法(我不能做什么)

为了说明我的问题,我创建了 2 个class Parent实例,每个实例都添加了class Child的实例。

from datetime import datetime, timedelta

class Child:
def __init__(self):
pass
def ask_time(self):                     # This function doesn't work,
return self.read_time()             # But I would like to be able to call here the "read_time()" method of the class "Parent"

class Parent:
def __init__(self, name, minutes_fast):
self.name = name
self.minutes_fast = minutes_fast
self.children = {}
def add_child(self, name):              # Construct "Child" class instance from class "Parent" class instance
self.children[name] = Child()       # Because of this line, I cannot inherit "class Child (Parent):"
def get_child(self, name):
if name not in self.children:
self.add_child(name)
return self.children[name]
def read_time(self):
current_time = datetime.now()
delta = timedelta(minutes=self.minutes_fast)
return (current_time + delta).strftime("%H:%M:%S")

# Add the Parent "James" who is 3 minutes early to his watch, and add him the child "John"
parent1 = Parent("James", 3)
child1 = parent1.get_child("John")
# Add the Parent "Michael" who is 1 minutes early to his watch, and add him the child "Matthew"
parent2 = Parent("Michael", 1)
child2 = parent2.get_child("Matthew")

print(parent1.read_time())
print(parent2.read_time())

在我的用例中,阅读时间是class Parent的责任。所以我将read_time()方法添加到了这个方法中。 但是,class Child的实例必须能够从创建它的class Parent的实例请求时间。所以我将ask_time()方法添加到调用class Parentread_time()方法的class Child中......如果不在我的类之间继承,这不起作用(从以下方式class Child(Parent):)。

这将允许我这样做,以及我现在需要做的事情。

print(child1.ask_time())
print(child2.ask_time())

但是当class Parent本身取决于class Child时,我不明白如何继承? 感谢您的帮助!

您将功能依赖与类继承混淆了。 您不必从Parent继承read_time。 事实上,您的实现表明这还不够。 当您正确设计时,read_time是一个实例属性:在不指定实例应响应Parent的情况下调用read_time是没有意义的。

您需要为每个子项提供对其父项的引用。 在add_child中包含以下内容:

def add_child(self, name):
baby = Child(self, name)
self.children[name] = baby

更改Child初始化以使用专有信息:

def __init__(self, parent, name):
self.parent = parent
self.name = name

让孩子的名字只是父母名单的属性似乎很愚蠢。

现在,当孩子需要问时间时,我们有:

def ask_time(self):
return self.parent.read_time()

最新更新