【问题标题】:AttributeError: 'super' object has no attribute 'compare_files'AttributeError:“超级”对象没有属性“比较文件”
【发布时间】:2018-07-15 04:00:22
【问题描述】:

具有按预期工作的继承示例代码。

class Animal:
    def action(self, value_1, p=None):
        print ('Parent action %d %d' % (value_1, p))
        return value_1 + 1 + p

class Dog(Animal):
    def action(self, value):
        print ('Dog action in child')
        return super(Dog, self).action(value, 1)

print(Dog().action(10))

以下是引发以下错误的另一个继承示例。

AttributeError: 'super' 对象没有属性 'compare_files'

class FileCompare:
    def compare_files(self, actual_filename, ref_filename, field_to_skip=None):
        return True

class MetaFileCompare(FileCompare):
    def compare_files(self, actual_file, ref_file):
        return super(FileCompare, self).compare_files(actual_file, ref_file,
                    0)

class WorkerFileCompare(FileCompare):
    def compare_files(self, actual_file, ref_file):
        return super(FileCompare, self).compare_files(actual_file, ref_file,
                    5)

print (WorkerFileCompare().compare_files('a', 'b'))

除了类名、方法名和返回类型外,代码几乎相同。听起来我错过了一些非常愚蠢的东西。没有拼写错误。能否指点一下?

【问题讨论】:

  • 修正了我犯的愚蠢错误。问题可以关闭
  • 您可以写一个答案来描述您如何修复它,然后自己接受答案,以便问题正确结束。这将保留它以防其他人将来遇到同样的问题。
  • 您可以按问题下方的删除按钮“关闭”您的问题。或者将您的问题恢复到原始状态并为您的问题写一个答案,这可能会使其他用户受益。
  • 当前状态下的问题将作为题外话手动关闭 -> 没有重现,因为您修复了代码中的错误,我们无法再重现该错误。
  • 添加了答案,但“您可以在 2 天内接受自己的答案”

标签: python inheritance


【解决方案1】:

改成

class MetaFileCompare(FileCompare):
    def compare_files(self, actual_file, ref_file):
        return super(FileCompare, self).compare_files(actual_file, ref_file,
                    0)

class MetaFileCompare(FileCompare):
    def compare_files(self, actual_file, ref_file):
        return super(MetaFileCompare, self).compare_files(actual_file, ref_file,
                    0)

这是我犯的愚蠢错误。

【讨论】:

  • 看起来您使用的是 Python 3。如果是这样,您根本不需要将任何参数传递给 supersuper().compare_files(actual_file, ref_file, 0) 也可以。
  • 有时简单的代码比较比对问题和解决方案的完整解释要好得多。对我来说,看上面 15 秒有助于解决我的问题,相比之下,看这个 (stackoverflow.com/questions/6075758/…) 15 分钟对我没有任何帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
相关资源
最近更新 更多