Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
2
Help us understand the problem. What is going on with this article?
@Tilmarle

属性

More than 5 years have passed since last update.

属性の実装

単純なパブリック属性で実装する

  • getやsetメソッドを使わない。
  • 単純なパブリック属性で実装することから始める。
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()

特別な振る舞いが必要な場合にpropertyデコレータを使う

  • 属性が設定されたときに特別な振る舞いが必要となる場合は@propertyデコレータとそれに対応するsetter属性をマイグレートする。
  • setter/getterの振る舞い複雑なものにならないように、複雑になる場合はメソッドにする。
  • @propertyを多用する必要があるなら元のクラスをリファクタリングすることも考える。
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()
2
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Tilmarle

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
2
Help us understand the problem. What is going on with this article?