Python静态setter和getter?

时间:2012-09-08 12:45:23

标签: python static

我已经为我的django应用程序添加了一个Jira客户端,现在需要将其设置为静态,但我无法确定如何将@property@?.setter转换为静态字段:

说我有课:

class nothing(object):
    auth_token = None
    counter = 0

    @property
    def a(self):
        self.log('getter')
        if not self.auth_token:
            self.auth_token = 'default'
        return self.auth_token

    @a.setter
    def a(self, value):
        self.log('setter')
        self.auth_token = value

    def log(self, value):
        self.counter+=1
        print '{0} called / counter: {1}'.format(value, self.counter)

我希望它的方法是静态的:

class nothing:
    auth_token = None
    counter = 0

    @staticmethod
    def get_a():
        nothing.log('getter')
        if not nothing.auth_token:
            nothing.log('auth_token value is None, setting')
            nothing.auth_token = 'default'
        return nothing.auth_token

    @staticmethod
    def set_a(value):
        nothing.log('setter')
        nothing.auth_token = value

    @staticmethod
    def log(value):
        nothing.counter+=1
        print '{0} called / counter: {1}'.format(value, nothing.counter)

现在无法将get_a标记为@property,因为调用它将返回一个对象,而不是实际调用get_a。方法是我可以忍受的,但是有没有办法让getter / setter代替呢?

2 个答案:

答案 0 :(得分:5)

最简单的方法是使这个类成为单身。而不是使方法静态,使用其实例覆盖类:

nothing = nothing()

如果您想拥有多个实例,也可以使用元类。

http://en.wikibooks.org/wiki/Python_Programming/MetaClasses

答案 1 :(得分:1)

你需要python中的类属性吗?

这是吸气剂的解决方案。对于setter,需要一个比类型更多的元类。

>>> class CP(object):
    def __init__(self, getter, setter = None):
        self._getter = getter
        self._setter = setter

    def setter(self, setter):
        self._setter = setter
    def __get__(self, obj, cls = None):
        print '__get__', obj, cls
        return self._getter(cls) # for static remove cls from the call
    def __set__(self, *args):
        print args


>>> class X(object):
    @CP
    def g(cls):
        print 'g', cls
        return 1


>>> X.g # getting returns value of g
__get__ None <class '__main__.X'>
g <class '__main__.X'>
1
>>> X().g
__get__ <__main__.X object at 0x02ACEC50> <class '__main__.X'>
g <class '__main__.X'>
1
>>> X.g = 3 # setting does not work
>>> X.g
3

但是当我看一眼时:

>>> X().g = 3
(<__main__.X object at 0x02ACEE50>, 3)

似乎不适用于课堂上__set__的属性。这是明智的,因为:如果调用了property,你甚至还能够在课堂上覆盖__set__