attribute

Implementation of attributes

Implement with simple public attributes

--Do not use get or set methods. --Start by implementing with simple public attributes.

python


class Book:
    def __init__(self, title):
        self.title = title
        self.page = 0
        self.isbn10 = ''

def main():
    b = Book('python book')
    b.page = 100
    b.page += 1
    print b.page

if __name__ == '__main__':
    main()

Use property decorators when you need special behavior

--Migrate the @ property decorator and its corresponding setter attribute if you need special behavior when the attribute is set. --Behavior of setter / getter Make a method when it becomes complicated so as not to make it complicated. --If you need to make heavy use of @property, consider refactoring the original class.

python


class Book(object):
    def __init__(self, title):
        self.title = title
        self.page = 0
        self.isbn10 = ''

class BookEx(Book):
    def __init__(self, title):
        super(BookEx, self).__init__(title)
        self._page = 0

    @property
    def page(self):
        return self._page

    @page.setter
    def page(self, page):
        # something do need.
        self._page = page

def main():
    b = Book('python book')
    b.page = 100
    b.page += 1
    print b.page

if __name__ == '__main__':
    main()

Recommended Posts

attribute
attribute
Python attribute alias