简体   繁体   English

如何使用类方法获取类列表的实例变量?

[英]How to get instance variable of a class list by using a class method?

sorry if it is a too easy question but I am just a beginner in python and watching some tutorial videos on classes.抱歉,如果这是一个太简单的问题,但我只是 Python 的初学者,正在观看一些有关课程的教程视频。 I tried to add something by myself but couldn't.我试图自己添加一些东西,但不能。 Here is the code :这是代码:

class Dog:
    dogs = []

    def __init__(self, name):
        self.name = name
        self.dogs.append(self)
    
    @classmethod
    def num_dogs(cls):
        return len(cls.dogs)

    @classmethod
    def dogs_names(cls):
        for i in cls.dogs:
            return cls.dogs[i.name]
    
    @staticmethod
    def bark(n):
        """barks n times"""
        for _ in range(n):
            print("Bark! ")
 
        
tim = Dog("Tim")
jim = Dog("Jim")
print(Dog.num_dogs())
print(Dog.dogs_names())

So I know dogs_names() method looks dumb, but I hope you understand my point.所以我知道 dog_names() 方法看起来很愚蠢,但我希望你明白我的意思。 I can reach the dogs list by only returning cls.dogs each time but how do I reach name variables of each item in the list?我可以通过每次只返回 cls.dogs 来访问狗列表,但是如何访问列表中每个项目的名称变量?

Thank you for your help.谢谢您的帮助。

You can do :你可以做 :

class Dog:
    dogs = []

    def __init__(self, name):
        self.name = name
        self.dogs.append(self)
        
    @classmethod
    def num_dogs(cls):
        return len(cls.dogs)

    @classmethod
    def dogs_names(cls):
        names = []  # create a new list
        for i in range(len(cls.dogs)):
            names.append(cls.dogs[i].name)  # append each name one by one to the list
        return names  # return the full list at the end
        
    @staticmethod
    def bark(n):
        """barks n times"""
        for _ in range(n):
            print("Bark! ")
 
        
tim = Dog("Tim")
jim = Dog("Jim")
print(Dog.num_dogs())
print(Dog.dogs_names())


you can also use list conprehension :您还可以使用列表理解:

    @classmethod
    def dogs_names(cls):
        return [dog.name for dog in cls.dogs]

There are two things wrong:有两点不对:

  1. You are returning immediately, rather than allowing a list of results to be built.您将立即返回,而不是允许构建结果列表。
  2. i is an instance of Dog , so i.name is a dog name, not an index in to the list of Dog indices. iDog一个实例,所以i.name是狗的名字,而不是Dog索引列表中的索引。

You build the list first, then return it after the loop is done building the list.您首先构建列表,然后在循环完成构建列表后返回它。

@classmethod
def dogs_names(cls):
    dog_names = []
    for i in cls.dogs:
        dog_names.append(i.name)
    return dog_names

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM