简体   繁体   中英

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? or is there a way to combine all these setter methods so that Property method can access all the instance variables one by one?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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