[英]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)'''
I am trying to put all these setter methods inside one property method?我正在尝试将所有这些 setter 方法放在一个属性方法中? or is there a way to combine all these setter methods so that Property method can access all the instance variables one by one?或者有没有办法组合所有这些setter方法,以便Property方法可以一个一个地访问所有实例变量?
If you want to make property in your class you have to add @property
decorator before function, and @name_of_property.setter
before setter function.如果要在 class 中创建属性,则必须在 function 之前添加@property
装饰器,并在设置器 ZC1C425268E68385D1AB5074C17A94 之前添加@name_of_property.setter
。
For example:例如:
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.