[英]Setter method in Property Method
class Book:
def __init__(self):
self.title=input("Enter a book name:")
self.author=input("Enter book author:")
self.publisher=input("Enter book publication:")
self.price=int(input("Enter book price:"))
def get_book(self):
print(self.title)
print(self.author)
print(self.publisher)
print(self.price)
def set_title(self, title):
self.title=title
def set_author(self, authr):
self.author=authr
def set_publisher(self, publish):
self.publisher=publish
def set_price(self, price):
self.price=price
Book=property(get_book, set_book)'''
我正在嘗試將所有這些 setter 方法放在一個屬性方法中? 或者有沒有辦法組合所有這些setter方法,以便Property方法可以一個一個地訪問所有實例變量?
如果要在 class 中創建屬性,則必須在 function 之前添加@property
裝飾器,並在設置器 ZC1C425268E68385D1AB5074C17A94 之前添加@name_of_property.setter
。
例如:
class Book:
def __init__(self):
self.title=input("Enter a book name:")
self.author=input("Enter book author:")
self.publisher=input("Enter book publication:")
self.price=int(input("Enter book price:"))
@property
def book(self):
print(self.title)
print(self.author)
print(self.publisher)
print(self.price)
@book.setter
def book(self,value):
#your code, for example:
print(value)
def set_title(self, title):
self.title=title
def set_author(self, authr):
self.author=authr
def set_publisher(self, publish):
self.publisher=publish
def set_price(self, price):
self.price=price
book = Book()
book.book#will print out title,author,publisher
book.book=30#will print 30
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.