[英]How to iterate over all the instances of a class?
因此,我知道以前已經有人問過這個問題,但是我找不到我的問題的答案,所有的答案都讓我更加困惑。
因此,我創建了一個名為Books的類,該類將文件的位置和文件名作為輸入,並具有一種稱為countwords的方法,該方法可對文件的單詞進行計數。
我創建了此類的一堆實例(它們被稱為嗎?),但我不想在所有實例上迭代CountWords方法。 這是我的代碼:
class Books():
def __init__(self, path, fullname):
self.path = path
self.fullname = fullname
def count_words(self):
try:
with open(self.path + self.fullname, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {self.fullname} doesn't exist.")
else:
words = contents.split()
num_words = len(words)
print(f"The file {self.fullname} has about {num_words}"
f"words.")
alice = Books("text_files/", 'alice.txt')
siddharta = Books("text_files/", 'siddhartha.txt')
mobydick = Books('text_files/', 'moby_dick.txt')
little_women = Books('text_files/', 'little_women.txt')
我不會寫這樣的東西:
for book in Books.list():
book.count_words()
並得到:
The file alice.txt has about 29465 words.
The file siddhartha.txt has about 1500 words.
The file moby_dick.txt has about 215830 words.
The file little_women.txt has about 189079 words.
打印與Books()類關聯的所有實例的單詞計數,如何實現呢? 謝謝!
編輯 :我嘗試了不同的方法,但這是我現在正在使用的一種:
碼:
# 1
import weakref
class Book():
# 2
book_list = []
def __init__(self, path, fullname):
self.path = path
self.fullname = fullname
# 3
self.__class__.book_list.append(weakref.proxy(self))
def count_words(self):
try:
with open(self.path + self.fullname, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {self.fullname} doesn't exist.")
else:
words = contents.split()
num_words = len(words)
print(f"The file {self.fullname} has about {num_words} "
f"words. ")
alice = Book("text_files/", 'alice.txt')
siddharta = Book("text_files/", 'siddhartha.txt')
mobydick = Book('text_files/', 'moby_dick.txt')
little_women = Book('text_files/', 'little_women.txt')
# 4
for book in Book.book_list:
book.count_words()
而不是你的類繼續引用已創建的所有情況下,我建議你先定義你的數據,然后創建從數據實例的集合。
例如:
book_paths = [('text_files/', 'alice.txt'),
('text_files/', 'siddharta.txt'),
('text_files/', 'moby_dick.txt'),
('text_files/', 'little_women.txt')]
books = []
for path, name in book_paths:
book = Books(path, name)
books.append(book)
book.count_words()
您還可以稍后遍歷books
以執行所需的任何操作。 使用list
推導的另一種方法:
books = [Books(path, name) for path, name in book_paths]
for book in books:
book.count_words()
您要做的就是創建一個類變量,該變量將在實例化實例時存儲書籍信息。
然后公開一個類級別的方法,該方法將在調用Books.list
時返回此列表。
這是相同的代碼
class Books(object):
_books_list = list()
def __init__(self, path, fullname):
self.path = path
self.fullname = fullname
self._books_list.append(self.path + self.fullname)
def count_words(self):
try:
with open(self.path + self.fullname, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {self.fullname} doesn't exist.")
else:
words = contents.split()
num_words = len(words)
print(f"The file {self.fullname} has about {num_words}"
f"words.")
@classmethod def list(): return self._books_list
alice = Books("text_files/", 'alice.txt')
siddharta = Books("text_files/", 'siddhartha.txt')
mobydick = Books('text_files/', 'moby_dick.txt')
little_women = Books('text_files/', 'little_women.txt')
那是解決問題的錯誤方法。
我建議您改為創建一個類字典,以文件名作為鍵:
代替:
alice = Books("text_files/", 'alice.txt')
siddharta = Books("text_files/", 'siddhartha.txt')
mobydick = Books('text_files/', 'moby_dick.txt')
little_women = Books('text_files/', 'little_women.txt')
做:
books_dict = {name:Books('text_files/',name+".txt") for name in ["alice","siddhartha","moby_dick","little_women"}
現在,您有了一個Books
實例的字典。 您現在可以像這樣迭代它:
for book_name,book_instance in books_dict.items():
print(book_name,book_instance)
如果要“注銷”實例,請執行以下操作:
books_dict.pop("alice")
最好不要為x個實例創建x個變量。 使用聯合結構。
從您的變量來看,通過命名Book
類可能更容易理解:
class Book():
def __init__(self, path, fullname):
self.path = path
self.fullname = fullname
def count_words(self):
try:
with open(self.path + self.fullname, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {self.fullname} doesn't exist.")
else:
words = contents.split()
num_words = len(words)
print(f"The file {self.fullname} has about {num_words}"
f"words.")
按照您的描述制作書籍實例
alice = Book("text_files/", 'alice.txt')
siddharta = Book("text_files/", 'siddhartha.txt')
mobydick = Book('text_files/', 'moby_dick.txt')
little_women = Book('text_files/', 'little_women.txt')
並將它們添加到被稱為books
的列表中:
books = [alice, siddhartha, mobydick, little_women]
然后您可以遍歷列表,在每本書上調用count_words
方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.