我有两个类以一对多的关系相互引用(Kid
在Toy
下面的示例中)。当我分配一个新Toy
的到时Kid
,我也希望Kid
分配到Toy
。
根据toys
属性列表创建自定义类并重新定义方法(例如append
,, )会起作用extend
,delete
但我想知道是否有更好的方法。
class Toy:
def __init__(self, name, kid=None):
self.name = name
self.kid = kid
class Kid:
def __init__(self, name, toys):
self.name = name
self.toys = toys
@property
def toys(self):
return self._toys
@toys.setter
def toys(self, val):
self._toys = val
# Assign the kid to the toys
for toy in self._toys:
toy.kid = self
if __name__ == "__main__":
toys = [Toy('Woodie'), Toy('Slinky'), Toy('Rex')]
andy = Kid('Andy', toys)
# Andy corrected assigned to toys
for toy in andy.toys:
print('{}\t{}'.format(toy.name, toy.kid.name))
print('-')
# Add new toy
andy.toys.append(Toy('Buzz'))
# Throws error because Buzz is not assigned Andy
for toy in andy.toys:
print('{}\t{}'.format(toy.name, toy.kid.name))
输出:
Woodie Andy
Slinky Andy
Rex Andy
-
Woodie Andy
Slinky Andy
Rex Andy
Traceback (most recent call last):
File "c:/Users/jonat/Desktop/tests/inheritance_q.py", line 34, in <module>
print('{}\t{}'.format(toy.name, toy.kid.name))
AttributeError: 'NoneType' object has no attribute 'name'
我想Buzz
被分配Andy
。