[英]How to get instance variable of a class list by using a class method?
抱歉,如果這是一個太簡單的問題,但我只是 Python 的初學者,正在觀看一些有關課程的教程視頻。 我試圖自己添加一些東西,但不能。 這是代碼:
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())
所以我知道 dog_names() 方法看起來很愚蠢,但我希望你明白我的意思。 我可以通過每次只返回 cls.dogs 來訪問狗列表,但是如何訪問列表中每個項目的名稱變量?
謝謝您的幫助。
你可以做 :
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())
您還可以使用列表理解:
@classmethod
def dogs_names(cls):
return [dog.name for dog in cls.dogs]
有兩點不對:
i
是Dog
一個實例,所以i.name
是狗的名字,而不是Dog
索引列表中的索引。您首先構建列表,然后在循環完成構建列表后返回它。
@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.