如何列出子类的所有实例?

时间:2018-03-01 05:07:53

标签: python

所以我正在寻找一种通过常规方法或classmethod列出子类的所有实例的方法。 例如:

class Player:

    def __init__(self,role, abilities, visiting, unique,Type)
        self.role = role
        self.abilities = abilities
        self.unique = unique
        self.visiting = visiting
        self.Type= Type

class Town(Player):
    def __init__(self,role,abilities,visiting,unique,Type):
        super().__init__(role,abilities,visiting,unique,Type)

Bodyguard= Town('Bodyguard', 'Choose someone to protect','Yes','No', 'Town Protective')
Crusader = Town('Crusader','Protect someone each night','Yes','No','Town Protective')
         .
         .
         .

我希望能够对所有Type='Town Protective'进行分组并打印出它们的列表。例如

print(Town_Protectives)

显示器:

['Bodyguard','Crusader'....]

这只是一个用来帮助我学习Python的小项目,所以它并不严肃。感谢您所有的帮助!

2 个答案:

答案 0 :(得分:2)

Bodyguard= Town('Bodyguard', 'Choose someone to protect','Yes','No', 'Town Protective')
Crusader = Town('Crusader','Protect someone each night','Yes','No','Town Protective')
Town_Protectives = [Bodyguard,Crusader]
print([p.role for p in Town_Protectives if p.Type == 'Town Protective'])

答案 1 :(得分:0)

这样做的一个简洁方法是使用一个class-attribute来保持对该类上创建的每个对象的显式引用,然后直接访问该类,或者使用classmethod来过滤所需的isntances。

class Player:

    _register = []

    def __init__(self,role, abilities, visiting, unique,Type)
        self.role = role
        self.abilities = abilities
        self.unique = unique
        self.visiting = visiting
        self.Type= Type
        self.__class__._register.append(self) # the ".__class__." is not strictly needed;

    @classmethod
    def list(cls, Type=None):
        results = []
        for instance in self._results:
             if isinstance(instance, cls) and (Type is None or Type == instance.Type):
              results.append(instance)
        return results