0

我有两个类以一对多的关系相互引用(KidToy下面的示例中)。当我分配一个新Toy的到时Kid,我也希望Kid分配到Toy

根据toys属性列表创建自定义类并重新定义方法(例如append,, )会起作用extenddelete但我想知道是否有更好的方法。

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

4

1 回答 1

2

您可以在 Kid 类中添加一个方法:

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

    def give_toy(self, toy):
        toy.kid = self
        self.toys.append(toy)


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.give_toy(Toy('Buzz'))

    # Throws error because Slinky 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
Buzz    Andy
于 2019-07-23T14:09:35.850 回答