假设我有两个类,父级和子级,如下所示:
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
但是,我的子对象具有多个属性,我正在寻找一种更有效的方式来将子属性继承到父对象中
答案 0 :(得分:0)
您已概述了最简单,最容易使用的方法:
另一种方法可以通过元编程来完成,在该方法中,您拦截对父级的textarea
调用,并查看子级__getattribute__
,然后返回子级属性。