python @property
↓元ネタ。2.6からサポートされているようだ。
http://docs.python.org/library/functions.html
元ネタから引用。
結果
ゲッター・セッターをメソッド呼び出しっぽくなく呼び出せるので、
コードが見易くなる。
また、セッターを定義しなければread onlyな属性も簡単に定義可能。
結果
このプロパティの書き方はスレッド(threading.Thread)のプロセスID取得時に気付いた。
↓のように書かれていて、なんだろこれ?って。
http://docs.python.org/library/functions.html
元ネタから引用。
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
print 'setter is called.'
self._x = value
@x.deleter
def x(self):
print 'deleter is called.'
del self._x
if __name__ == '__main__':
c = C()
print c.x
c.x = 1
print c.x
del c.x
結果
None setter is called. 1 deleter is called.
ゲッター・セッターをメソッド呼び出しっぽくなく呼び出せるので、
コードが見易くなる。
また、セッターを定義しなければread onlyな属性も簡単に定義可能。
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
if __name__ == '__main__':
c = C()
print c.x
c.x = 1
print c.x
del c.x
結果
Traceback (most recent call last): File "C:\Users\user\workspace\test\src\mypac\test.py", line 35, inc.x = 1 AttributeError: can't set attribute None
このプロパティの書き方はスレッド(threading.Thread)のプロセスID取得時に気付いた。
↓のように書かれていて、なんだろこれ?って。
@property
def ident(self):
assert self.__initialized, "Thread.__init__() not called"
return self.__ident
コメント
コメントを投稿