How to use get/set methods?

佐手、 提交于 2019-12-05 07:21:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!