我希望 book1 在不定義的情況下自動創建,因為這將是一段代碼,所以我想要實作的是每次用戶填寫這些輸入時,它會創建 book1 然后是 book2 等等,最重要的是我可以再次呼叫它們
class Book(object): #this class stores books in detail
def __init__(self, title: str , author: str, isbn: int, genre: str, numCopies: int):
self._title: str = title
self._author: str = author
self._isbn: int = isbn
self._genre: str = genre
self._numCopies: int = numCopies
title = input("The Book's Title: ")
author = input("The Book's Author: ")
isbn = int(input("The Book's ISBN: "))
genre = input("The Book's Title: ")
numCopies = int(input("The Book's Copies: "))
book1 = Book(title,author,isbn,genre,numCopies)
uj5u.com熱心網友回復:
通常,當您有重復的代碼時,您可以為此撰寫一個函式。
這可以通過多種方式完成。其中之一是使用 aclassmethod作為您的類的另一個建構式:
class Book: # this class stores books in detail
def __init__(self, title: str, author: str, isbn: int, genre: str, numCopies: int):
self._title = title
self._author = author
self._isbn = isbn
self._genre = genre
self._numCopies = numCopies
@classmethod
def from_user_input(cls):
title = input("The Book's Title: ")
author = input("The Book's Author: ")
isbn = int(input("The Book's ISBN: "))
genre = input("The Book's Title: ")
numCopies = int(input("The Book's Copies: "))
return cls(title, author, isbn, genre, numCopies)
book1 = Book.from_user_input()
然后,您可以將實體附加到名為Booksexample 的串列/字典中。
注意 1:您不需要從objectPython 3 繼承。
注 2:如果您剛剛創建了此類來保存資料,請查看namedtuple. 它要輕得多。
注3:雖然可以在您的內部鍵入注釋變數__init__,但在您的情況下它是無用的。例如self._title,從引數獲取值,title并且您已經str在那里定義了該值。這是不必要的重復。靜態型別檢查器可以從引數本身提示您。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/532197.html
標籤:Python班级变量
上一篇:PHP-未定義型別“客戶”
下一篇:C#創建一個類元素串列以多次使用
