【问题标题】:How to get property names from super class in sub class python如何从子类python中的超类获取属性名称
【发布时间】:2017-10-19 10:43:36
【问题描述】:

我有一个像下面这样的课程

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 中提到了很多问题,但没有一个对我有帮助。谁能帮我解决这个问题。

【问题讨论】:

  • 你试过super(CachingPaginator,self).count吗?
  • 或者,如果您使用的是 python 3:super().count
  • @TheBrewmaster 我在 python 2.7 伙伴...
  • @lok​​esh1729 我的心向你倾诉 ;-)
  • @lok​​esh1729 最好将 python2.7 标签添加到您的问题以及edit中可能存在的任何其他约束

标签: python django python-2.7 inheritance


【解决方案1】:

属性只是类属性。要获取父类的类属性,您可以使用对父类 (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))

【讨论】:

    猜你喜欢
    • 2011-03-25
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 2012-01-08
    • 2021-12-04
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    相关资源
    最近更新 更多