有没有什么办法可以定义一个函数,可以在程序的某个稍后的位置为现有的__init__
方法添加新属性?例如,下面我为一个Family Tree创建了一个Class。每个实例都会创建一个根。
class FamilyTree:
def __init__(self,rootObj):
self.key = rootObj
我希望每个新的根实例都能够拥有特定数量的子属性:例如:
self.child1 = 'B'
self.child2 = 'C'
self.child3 = 'D'
由于每个新的根实例都可以包含不同数量的子项,因此如何将新属性可变地添加到__init__
方法中?
答案 0 :(得分:2)
我猜你真正(应该)想要的是list
个孩子:
class FamilyTree:
def __init__(self, rootObj):
self.key = rootObj
self.children = []
def add_children(*new_children)
self.children.extend(new_children)
现在您可以使用add_children
方法一次将任意数量的子项添加到列表中,或者您也可以直接访问children
实例成员列表:
tree = FamilyTree("whatever a rootObj is...")
tree.add_children("Alice", "Bob", "Claudia", "Dave")
tree.children.append("Eva")
tree.children += ["Fred", "Gina", "Herbert"]
print(tree.children)
# Output: ["Alice", "Bob", "Claudia", "Dave", "Eva", "Fred", "Gina", "Herbert"]
答案 1 :(得分:0)
class FamilyTree:
def __init__(self,rootObj):
self.key = rootObj
child1='B'
child2='C'
child3='D'
objold=FamilyTree('keyold')
FamilyTree.child1=child1
FamilyTree.child2=child2
FamilyTree.child3=child3
objnew=FamilyTree('keynew')
print objnew.key,objnew.child1,objnew.child2,objnew.child3
print objold.key,objold.child1,objold.child2,objold.child3
'''
keynew B C D
keyold B C D
'''
答案 2 :(得分:0)
也许我理解这是错误的,但是你没有为' init '方法添加属性,你将属性添加到类的实例中。 'self'指的是类的实例。 要在运行时将属性添加到类中,请查看Abhra的示例。 要将属性添加到类的特定实例,请查看此处(抱歉Abhra,偷走了您的示例):
class FamilyTree:
def __init__(self,rootObj):
self.key = rootObj
child1='B'
child2='C'
child3='D'
objold=FamilyTree('keyold')
objold.child1=child1
objold.child2=child2
objold.child3=child3
objnew=FamilyTree('keynew')
print objnew.key, objnew.child1, objnew.child2, objnew.child3
print objold.key, objold.child1, objold.child2, objold.child3
'''
keynew AttributeError: 'FamilyTree' object has no attribute 'child1' (same error for the others)
keyold B C D
'''
答案 3 :(得分:0)
自动执行此操作的可能方法如下:
class FamilyTree:
def __init__(self,rootObj, child_names=None):
self.key = rootObj
if child_names is not None:
# child_names is a list of child attributes values
for i, child in enumerate(child_names):
setattr(self, 'child{0}'.format(i), child)
setattr(self, 'child_nbr', len(child_names))
def add_child(self, *child_names)
for name in child_names:
self.child_nbr += 1
setattr(self, 'child{0}'.format(self.child_nbr), name)
用法:
>>> f=FamilyTree('Family1', ['B', 'C', 'D'])
>>> print(f.child1, f.child2, f.child3)
>>> i = 0
>>> while i < f.child_nbr:
>>> print getattr(f, 'child{0}'.format(i+1))
>>> f.add_child('E')
>>> print(f.child4)
>>> f.add_child('F', 'G')
>>> print(f.child5, f.child6)