【问题标题】:Can I inherit child object properties to parent object properties such that they change as child object changes?我可以将子对象属性继承到父对象属性,以便它们随着子对象的变化而变化吗?
【发布时间】:2020-01-21 00:48:54
【问题描述】:

假设我有两个类,父类和子类,如下所示:

class Child:
    def __init__(self, name):
        self.name = name

    def change_name(self, name):
        self.name = name

class Parent:
    def __init__(self, child):
        self.child = child
        self.childs = [child]

    def new_child (self, child):
        self.childs.append[child]
        self.child = child

现在,如果我创建子对象和父对象,那么我想从父对象调用子属性,如下例所示

child = Child('Nelson')
parent = Parent(child)

# I want to access child name from the parent object

print(parent.name) # should return parant.child.name <'Nelson'>

new_child = Child('Thomas')
parent.new_child(new_child)
print(parent.name) # should return the new name <'Thomas'>

# some code that will change the name of the child object
print(parent.name) # should return the new name

目前,我在返回子属性的 Parent 类中添加了一个属性装饰器

class Parent:
    def __init__(self, child):
        self.child = child
        self.childs = [child]

    def new_child (self, child):
        self.childs.append[child]
        self.child = child

    @property
    def name(self):
        return self.child.name

但是,我的子对象有多个属性,我正在寻找一种更有效的方法将子属性继承到父对象中

【问题讨论】:

  • 我不认为“将子属性继承到父对象”是非常正确的术语。这里没有继承——我们有水平相关的类,而不是垂直相关的类。孩子是公开的,所以我们可以继续使用额外的间接层parent.child.fooparent.child.baz = "quux"等访问所有属性。如果你想封装,那没关系,但不清楚是否需要眼下。请参阅 x-y problem 并可能在此处提供更多上下文。谢谢!

标签: python oop


【解决方案1】:

你已经概述了最清晰和最容易做到的:

  • 让父属性调用引用的子对象名称属性

另一种方法可以通过元编程完成,您可以拦截父级上的__getattribute__ 调用并查看子级hasattr,然后您将返回子级属性。

请看这里:Intercept method calls in Python

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2022-10-24
    • 2023-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多