繁体   English   中英

属性方法中的 Setter 方法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM