【问题标题】:Create child class instances from parent class instance, and call parent methods from child class instance从父类实例创建子类实例,并从子类实例调用父方法
【发布时间】:2021-08-28 19:00:42
【问题描述】:

我希望我能做两件事:

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

为了说明我的问题,我创建了两个 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 Parentread_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


【解决方案1】:

您将函数依赖与类继承混淆了。您不必从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()

【讨论】:

  • 谢谢@Prune,我理解你的想法和非常清楚的解释。这样做是最佳做法吗?因为我的印象是,这样做我们正在重载class Child 的实例,对吧?
  • “重载实例”是什么意思?标准做法是在开始编码之前设计类关系。您构想了父子关系,但没有遵循类交互中引用的需要。您可以查看 UML(统一建模语言)实践以了解如何使用设计阶段。
  • 我的意思是我感觉 Child 类的实例将包含比必要更多的信息。无论如何,它非常适合我的用例。
  • “但在类交互中没有遵循引用的需要”是什么意思?这是否意味着我可以不这样做?
  • 定义“必要”。是的,您可以继续保留父母中的所有信息。然后每次你想调用ask_time,你全局访问Parent类,搜索所有父母的所有孩子,直到找到当前的Child对象。这确定了向哪个父母询问时间。这不是有效的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-10
  • 1970-01-01
  • 2023-03-30
  • 2021-11-07
  • 1970-01-01
  • 2021-11-17
相关资源
最近更新 更多