我已经为我的 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()
如果你想拥有多个实例,你也可以使用元类。
关于Python 静态 setter 和 getter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12330823/