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

2024-05-29 08:28:33 发布

您现在位置: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的小项目,所以没什么大不了的。谢谢你的帮助


Tags: 方法selfinitdeftypeclassroleunique
2条回答

一种干净的方法是使用一个class属性来保持对在该类上创建的每个对象的显式引用,然后直接访问该类,或者使用一个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
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'])

相关问题 更多 >

    热门问题