【发布时间】:2021-08-28 19:00:42
【问题描述】:
我希望我能做两件事:
-
- 从父类的实例创建尽可能多的子类(我能做什么)
-
- 从子类的实例调用父类的方法(我不能做什么)
为了说明我的问题,我创建了两个 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 Child 中,该方法调用class Parent 的read_time() 方法......如果没有在我的类之间继承(从以下方式class Child(Parent):),它将无法工作。
这将允许我这样做,以及我现在需要做什么。
print(child1.ask_time())
print(child2.ask_time())
但是当class Parent 本身依赖于class Child 时,我看不到如何继承?
感谢您的帮助!
【问题讨论】:
-
您需要在创建
Child时显式传递Parent实例;Child.__init__()可能会将其存储在self.parent中,然后您可以使用self.parent.read_time()。 -
@jasonharper 谢谢。和 Prune 的回答是一样的想法
标签: python python-3.x class