我希望能够在具有子节点和孙节点的节点实例上链接方法。当我在该顶部节点上调用方法时,我希望能够返回该对象的子孙。我还希望能够从最顶层节点获取这些子孙的属性。我有以下数据模型:
class GrandParent(object):
def __init__(self,name='',age=0,is_retired=True,children=[]):
self.name = name
self.age = age
self.is_retired = is_retired
if children:
self.children = children
def print_mychildren(self):
for child in self.children:
print "Child: ",child
def mychildren(self):
return self.children
def __str__(self):
return "name: %s age: %s is_retired:%s" %(self.name,self.age,self.is_retired)
class Parent(object):
def __init__(self,name='',age=0,has_mortgage=True,children=[]):
self.name = name
self.age = age
self.has_mortgage = has_mortgage
if children:
self.children = children
def print_mychildren(self):
for child in self.children:
print "Child: ",child
def __str__(self):
return "name: %s age: %s has_mortgage: %s" %(self.name,self.age,self.has_mortgage)
class Child(object):
def __init__(self,name='',age=0,has_toys=True):
self.name = name
self.age = age
self.has_toys = has_toys
def __str__(self):
return "name: %s age: %s has_toys:%s" %(self.name,self.age,self.has_toys)
if __name__ == '__main__':
beaver = Child('Beaver',12,True)
ward = Child('Ward',16,False)
june = Parent('June',38,True,[beaver,ward])
grandpa = GrandParent('Grandpa',61,True,[june])
print grandpa
grandpa.print_mychildren() # print June
# Doesn't work
grandpa.mychildren().print_mychildren() # I want it to print Ward and Beaver
# Doesn't work
print grandpa.mychildren().mychild('Beaver').age # I want it to return an age
请注意,我想将 GrandParent、Parent 和 Child 类分开,因为我想为每个类赋予不同的属性,例如 has_mortgage 或 is_retired。
从上面的数据模型中,我希望能够链接方法以遍历顶部节点的子节点。它看起来像这样:
grandpa.children # returns a list of children
print grandpa.mychild('June').has_mortgage # returns the value
grandpa.mychildren().mychildren() # prints a list of grandchildren
print grandpa.mychildren().mychild('Ward').has_toys # return the value
换句话说,我可以发表声明吗:
print grandpa.mychildren().mychildren()
表现得像:
for child in grandpa.children:
for grandchild in child.children:
print grandchild
我将不胜感激您对此的回答。谢谢你。
伊利诺伊州保罗
芝加哥