我已经为我的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)
Run Code Online (Sandbox Code Playgroud)
我希望它的方法是静态的:
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)
Run Code Online (Sandbox Code Playgroud)
不能标记get_a为@property现在调用它将返回一个对象,而不是实际调用get_a.方法是我可以忍受的,但是有没有办法让getter/setter代替呢?
最简单的方法是使这个类单身.而不是使方法静态,使用其实例覆盖类:
nothing = nothing()
Run Code Online (Sandbox Code Playgroud)
如果要拥有多个实例,也可以使用元类.
http://en.wikibooks.org/wiki/Python_Programming/MetaClasses