1

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__()?

Opsa
  • 451
  • 3
  • 7
  • 12
  • 1
    Of course you should include `self.a = 0` or something like that in the `__init__` method, too. Also, you should not use trivial getters/setters in Python. Just change it directly: `Foo().a = 42`. If you have to validate your input, you should use `property.setter`. – Gandaro Feb 16 '12 at 18:10

2 Answers2

4

They are instance methods. You have to create an instance of Foo first:

f = Foo()
f.set(10)
f.get()    # Returns 10
mipadi
  • 398,885
  • 90
  • 523
  • 479
4

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
Eugene
  • 41
  • 2