【问题标题】:Field inheritance access in pythonpython中的字段继承访问
【发布时间】:2012-10-04 19:46:51
【问题描述】:

我遇到了继承问题。

这是我的主程序:

def main(argv):
  rfp = reqboxfileparserng() # Inherits from reqboxfileparser()
  rfp.importsdir = './data/'
  if rfp.parsingasutf8_win():
    rfp.parsefile("./data/LRCv12.txt")

以下是课程:

class reqboxfileparser():
  def __init__(self):
    ... removed code ...
    # Init mmap
    self.file = None
    self.f = None

  def parsefile(self, filename):
    # Public
    self.filename = filename

    # Init mmap
    self.file = codecs.open(filename, encoding='utf-8', mode='r') # open(filename, 'r')
    self.f = mmap.mmap(self.file.fileno(), 0, access=mmap.ACCESS_READ)
    self.f.seek(0) # rewind

    # Parsing stuff
    self.getfunlist()
    self.vlog(VERB_MED, "len(fun) = %d" % (len(self.funlist)))
    self.getfundict()
    self.vlog(VERB_MED, "fundict = %s" % (self.fundict))
... rest of reqboxfileparser() class code removed ...

class reqboxfileparserng(reqboxfileparser, object):
  def __init__(self):
    # Public
    reqboxfileparser.__init__(self)
    self.fundict = {}
    self.importsdir = ''

  def getfunlist(self):
    """
    Overrided method to load from a CSV file
    """
    self.funlist = []

    fh = open(self.importsdir + 'in-uc-objects.csv', 'rb')
    f = csv.reader(fh, delimiter=',')
  ... rest of the code removed, it works fine ...

  def getfundict(self):
    """
    Fills the fundict property with a dict where each element is indexed
    by the fun name and each value is an object from the model
    """
    self.__fundict = {}

    beginloc = self.bodystartloc()

    # PROBLEM!

    finalloc = super(reqboxfileparser, self).f.size() - 1
    ... rest of the code removed ...

如您所见,我有两个类,第一个是 reqboxfileparser(),第二个是继承自第一个的 reqboxfileparserng()。

在主程序上,我调用方法: parsefile("./data/LRCv12.txt") [not overrided] 后来在第二个类上调用 getfunddict() [overrided],但是当我尝试访问 f. size() 它总是以 TypeError 失败:必须是类型,而不是 classobj。

自从我不使用继承开发类以来已经有一段时间了,但如果我没记错的话,这些概念是正确的。我是 Python 的新手。

有什么帮助吗?

非常感谢。

【问题讨论】:

  • 值得注意的是,Python 约定是类名位于CapWords - 检查the python style guide
  • 你能发布错误信息,而不是描述它吗?

标签: python oop inheritance


【解决方案1】:

这里有两个问题:

超级类和老式类:

class reqboxfileparser(): 不继承自 object,因此,super(reqboxfileparser, self) 将始终产生错误:

TypeError: must be type, not classobj.

继承类中不正确的超级调用:

您正在执行super(reqboxfileparser, self),但您将继承的类 (reqboxfileparser) 作为第一个参数传递,而不是继承类。

因此,Python 会尝试查找 reqboxfileparser 继承的类,该类实现您正在寻找的内容:f

但这不是你想要的:你想要实现freqboxfileparserng 的祖先;那将是reqboxfileparser

have a look at the documentation 了解最常见的super 调用语法。

您的解决方案

您现在可能已经猜到您应该改用super(reqboxfileparserng, self)

另外,您应该始终使用new-style classes(但仅此一项并不能解决您的问题,您会收到一个不同的错误,抱怨AttributeError: 'super' object has no attribute 'f',即True,因为object 不提供f)。

最后一件事......

但是在这里,您还有最后一期!

您试图引用f,它是子类实例的属性。当您使用 super 调用时,此属性不存在,因为它不存在于父类的类定义中,而父类定义是 super 调用将使用的。 (在__init__ 方法中)

我不会更详细地说明为什么这对 super 很重要,但我的想法是基本上只将super 用于在类级别定义的内容。通常,方法是,因此它们非常适合 super 调用。

这是一个描述我的意思的例子:

class reqboxfileparser():
    g = 'THIS IS G'

    def __init__(self):
        self.f = 'THIS IS F'
        self.g = 'THIS IS NEW G'

    def get_g(self):
        return self.g

class reqboxfileparserng(reqboxfileparser, object):
    def __init__(self):
        reqboxfileparser.__init__(self)


    def getfundict(self):
        print super(reqboxfileparserng, self).g # Prints "THIS IS G"
        print super(reqboxfileparserng, self).get_g() # Prints "THIS IS NEW G"
        print super(reqboxfileparserng, self).f # This raises an AttributeError

if __name__ == '__main__':
    o = reqboxfileparserng()
    o.getfundict()

总的来说,super 调用与使用ParentClass.stuff 非常相似,只是它更好地处理了多重继承,因此应该使用它。

您可以在这里看到,reqboxfileparser.f 会引发 AttributeError


脚注:classobj 是旧式类,type 是新式类。

【讨论】:

  • 感谢您的详细回答,Thomas,但我仍然没有完全明白。我改了类reqboxfileparser(object),所以继承自object,我改了father = super(reqboxfileparserng, self),然后分别调用finalloc =father.f.size() - 1.什么不懂仍然得到你说的错误:AttributeError:'super'对象没有属性'f'。我不应该通过这种方式使用 super 来引用 reqboxfileparser 吗?
  • @AlbertDeLaFuente 如果你告诉我什么还没有完全得到,我可以帮你吗?
  • 对不起,我早点进入,我编辑了之前的帖子。再次感谢!
【解决方案2】:

您缺少的一点是 fcurrent 类的一个属性。它是继承的:当您调用super(...).__init__() 时,代码将f 设置为self。因此,要从子类访问它,您只需执行self.f,就像任何其他属性一样。

任何属性或方法都是如此。当您的子类实际上覆盖了某些内容并且您需要调用超类的版本时,您只需要使用super。所以不需要调用 super 来访问parsefile,例如:self.parsefile() 就可以了。

【讨论】:

  • 非常感谢丹尼尔的回答。我想我可能从一开始就忘记了自我,我认为这是一个继承问题......我是一个天才! =(
  • ... 到底是什么super(...).__init__()
猜你喜欢
  • 1970-01-01
  • 2012-09-27
  • 1970-01-01
  • 1970-01-01
  • 2019-05-14
  • 2018-03-05
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多