2017-10-19 168 views
0

超類獲得的屬性名稱我有一個像下面如何從子類蟒蛇

class Paginator(object): 
    @cached_property 
    def count(self): 
     some_implementation 

class CachingPaginator(Paginator): 
    def _get_count(self): 
     if self._count is None: 
      try: 
       key = "admin:{0}:count".format(hash(self.object_list.query.__str__())) 
       self._count = cache.get(key, -1) 
       if self._count == -1: 
        self._count = self.count # Here, I want to get count property in the super-class, this is giving me -1 which is wrong 
        cache.set(key, self._count, 3600) 
      except: 
       self._count = len(self.object_list) 
    count = property(_get_count) 

如上評論指出一類,self._count = <expression>應該得到超一流的計數屬性。如果是方法我們可以這樣稱呼它012AYAFAIK。我提到過很多問題,但沒有一個能幫助我。任何人都可以幫助我。

+1

而你嘗試過'超(CachingPaginator,個體經營).count'? –

+0

或者,如果你是在python 3上:'super()。count' –

+0

@TheBrewmaster我在python 2.7 mate上... –

回答

0

屬性只是類屬性。要獲得父級的屬性,可以使用直接查找父類(Paginator.count)或super()調用。現在,在這種情況下,如果你在父類中使用直接查找,你必須手動調用描述符的協議,這是一個有點冗長,因此使用super()是最簡單的解決方案:

class Paginator(object): 
    @property 
    def count(self): 
     print "in Paginator.count" 
     return 42 

class CachingPaginator(Paginator): 
    def __init__(self): 
     self._count = None 

    def _get_count(self): 
     if self._count is None: 
      self._count = super(CachingPaginator, self).count 
     # Here, I want to get count property in the super-class, this is giving me -1 which is wrong 
     return self._count 
    count = property(_get_count) 

如果你想有一個直接父類的查找,替換:

self._count = super(CachingPaginator, self).count 

​​