【问题标题】:How can I use a function of an inherited 'mother' class from within the 'child class'?如何从“子类”中使用继承的“母”类的功能?
【发布时间】:2012-03-09 02:49:21
【问题描述】:

我有一个继承自 Writer 类的 CsvWriter 类。 Writer 类有一个函数 getInfo,我想在多个“子”类中使用它。但是当我从 CsvWriter 类调用 getInfo 函数时,我得到了这个错误:

TypeError: unbound method getInfo() must be called with Writer instance as first argument (got Element instance instead)

所以因为 Writer 类还没有被实例化,所以我不能调用 getInfo。但我不想实例化它(我认为),因为我想从“子”类中调用它。如何从 CsVwriter() 调用该函数?

下面是两个类:

class Writer():
    def __init__(self, path, readerInstance):
        self.path = path
        self.readerInstance = readerInstance
        return

    def getInfo(self, element):
        print element


class CsvWriter(Writer):
    def __init__(self,path, readerInstance):
        self.path = path
        self.readerInstance = readerInstance
        for feature in readerInstance.getFeatures():
            Writer.getInfo(feature)
        return

我这样运行它们:

filePath = '/homes/ndeklein/test.featureXML'
elements = featXML.Reader(filePath)
featXML.CsvWriter('test.csv', elements)

【问题讨论】:

  • 子类继承所有方法。只需致电self.getInfo(...)。否则你为什么要设置继承呢?

标签: python class function inheritance


【解决方案1】:

Writer.getInfo() 替换为self.getInfo()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多