2012-09-08 103 views
2

我已經把吉拉客戶對我的Django應用程序一起,現在需要讓靜態的,但我想不出如何@property@?.setter轉換成靜態字段:Python靜態setter和getters?

說我有一個類:

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現在和調用它會返回一個對象,而不是ACTU盟友電話get_a。方法是我可以忍受的,但是有沒有辦法讓getter/setter改爲?

回答

0

你需要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__。這是明智的,因爲:如果調用__set__,你甚至可以在課堂上覆蓋例如property