4

我已经为我的 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@propertynow 因为调用它将返回一个对象而不是实际调用get_a. 方法是我可以忍受的东西,但是有没有办法让 getter/setter 代替?

4

2 回答 2

6

最简单的方法是使这个类单例。与其将方法设为静态,不如用其实例覆盖类:

nothing = nothing()

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

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

于 2012-09-08T12:50:10.640 回答
1

你需要python中的类属性吗?

这是getter的解决方案。对于 setter,需要除 type 之外的其他元类。

>>> 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在课堂上的 a ?__set__

于 2012-09-08T15:30:45.463 回答