私のコードのどこにバグを指摘してください。get/setメソッドの使い方は?
class Foo:
def get(self):
return self.a
def set(self, a):
self.a = a
Foo.set(10)
Foo.get()
はTypeError:セット()__get__()
/__set__()
を使用する方法
正確に2位置引数(1が指定された)を取りますか?
私のコードのどこにバグを指摘してください。get/setメソッドの使い方は?
class Foo:
def get(self):
return self.a
def set(self, a):
self.a = a
Foo.set(10)
Foo.get()
はTypeError:セット()__get__()
/__set__()
を使用する方法
正確に2位置引数(1が指定された)を取りますか?
How to use
__get__()/__set__()
?
をあなたはのpython3を持っている場合:あなたは、最初のFoo
のインスタンスを作成する必要があります。 Python2.6の記述子は私のためにはうまく動作しません。
のPython v2.6.6
>>> class Foo(object):
... def __get__(*args): print 'get'
... def __set__(*args): print 'set'
...
>>> class Bar:
... foobar = Foo()
...
>>> x = Bar()
>>> x.foobar
get
>>> x.foobar = 2
>>> x.foobar
2
のPython v3.2.2はもちろん
>>> class Foo(object):
... def __get__(*args): print('get')
... def __set__(*args): print('set')
...
>>> class Bar:
... foobar = Foo()
...
>>> x = Bar()
>>> x.foobar
get
>>> x.foobar = 2
set
>>> x.foobar
get
は 'self.a = 0 'または' __init__'方法でそのようなことは、あまりにも含めるべきです。また、Pythonでは簡単なgetter/setterを使用しないでください。それを直接変更してください: 'Foo().a = 42'。入力を検証する必要がある場合は、 'property.setter'を使用してください。 – Gandaro