问题
Please point where a bug in my code.
class Foo:
def get(self):
return self.a
def set(self, a):
self.a = a
Foo.set(10)
Foo.get()
TypeError: set() takes exactly 2 positional arguments (1 given)
How to use __get__()
/__set__()
?
回答1:
They are instance methods. You have to create an instance of Foo
first:
f = Foo()
f.set(10)
f.get() # Returns 10
回答2:
How to use
__get__()/__set__()
?
Like this if you have Python3. Descriptors in Python2.6 doesn't want works properly for me.
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
来源:https://stackoverflow.com/questions/9316598/how-to-use-get-set-methods