Python 静态 setter 和 getter?

标签 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?

最佳答案

最简单的方法是让这个类成为单例。不要将方法设为静态,而是用实例覆盖类:

nothing = nothing()

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

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

关于Python 静态 setter 和 getter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12330823/

相关文章:

java - 仅当外部类参数化时内部接口(interface)才会生成错误?为什么?

c - 动态二维数组转静态数组

c++ - 我怎样才能明智地分配静态 RtMidi 回调对象?

python - Pandas str.contains,包含所有给定的字符

java - 自动从 pdf 中提取许多文件的文本

python - 轻松启动多个rq工作进程——水平扩展

c - 共享库中的静态变量

html - 这个背景图像是如何工作的?

Python WebKitWebView : how to get (generated) source code

python - 如何根据属性访问类型(使用类或实例)在函数之间创建 "switch"?