5
1

More than 3 years have passed since last update.

Python 3.9 で class property を作る

Last updated at Posted at 2021-07-17

Python 3.9 から @classmethod@property の重ねがけができるようになった事に気づきました。

バージョン 3.9 で変更: Class methods can now wrap other descriptors such as property().
https://docs.python.org/ja/3.9/library/functions.html#classmethod

ということで、早速実験してみました。

>>> class Foo:
...     @classmethod
...     @property
...     def prop(self):
...         print('Hello class property!')
...         return "hello"

こういうクラスを作っておいて、クラス属性 prop を呼び出すと、メソッドが呼び出され、値が返ります。

>>> Foo.prop
Hello class property!
'hello'

ちなみに、インスタンス化したあともプロパティとして動作します。

>>> Foo().prop
Hello class property!
'hello'

これまであまり class property を作ろうと思ったことがなかったのですが、面白い使いみちがないか考えてみようと思います。

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1