2017-10-19 5 views
0

でスーパークラスからプロパティ名を取得するにはどのように私は上記のコメントで示されているようには、サブクラスのpython

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>がスーパークラスのCountプロパティを取得する必要があります。メソッドの場合は、 super(CachingPaginator,self).count() AFAIKのように呼び出すことができます。私はSOの中で多くの質問をしてきましたが、それは私を助けませんでした。誰もがこれで私を助けることができますか?

+1

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

をそして、あなたは 'スーパー(CachingPaginator、自己).count'を試してみましたか? –

+0

もしあなたがpython 3であれば: 'super()。count' –

+0

@TheBrewmaster私はPython 2.7のメイトです... –

答えて

0

プロパティは単なるクラス属性です。親のクラス属性を取得するには、親クラス(Paginator.count)または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) 

:あなたが親クラスに直接ルックアップを使用する場合は、この場合には、あなたは少し冗長である、手動で記述プロトコルを起動する必要がありますさて、そうsuper()を使用する最も簡単なソリューションです。直接の親クラスの検索、置き換え:

​​
関連する問題