【发布时间】: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.foo、parent.child.baz = "quux"等访问所有属性。如果你想封装,那没关系,但不清楚是否需要眼下。请参阅 x-y problem 并可能在此处提供更多上下文。谢谢!