[英]How to get property names from super class in sub class 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中提到了许多问题,但没有一个对我有帮助。 谁能帮我这个忙。
属性只是类属性。 要获取父类的class属性,可以在父类上使用直接查找( 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
与
self._count = Paginator.count.__get__(self, type(self))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.