How to use get/set methods?

为君一笑 提交于 2019-12-03 21:44:32

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

f = Foo()
f.set(10)
f.get()    # Returns 10

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