2017-10-19 157 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 

​​