我正在研究 MIT 6.00 OCW 问题集之一,我有以下代码...
class Trigger(object):
def evaluate(self, story):
"""
Returns True if an alert should be generated
for the given news item, or False otherwise.
"""
raise NotImplementedError
# Whole Word Triggers
# Problems 2-5
# WordTrigger
class WordTrigger(Trigger):
def __init__(self, word):
self.word = word
def is_word_in(self, text):
word = self.word.lower()
text = text.lower()
#Remove punc and split text
for ch in string.punctuation:
text = text.replace(ch, ' ')
splitText = text.split(' ')
#Check if word is in text
return word in splitText
# TitleTrigger
class TitleTrigger(WordTrigger):
## def __init__(self, word):
## self.word = word
def evaluate(self, story):
return self.is_word_in(story.get_title())
我最初没有注释掉 TitleTrigger()
中的构造函数,但是当我运行提供的测试脚本时,当测试实用程序试图调用我的 TitleTrigger()< 时它抛出了一个错误
类。我无法弄清楚哪里出了问题,所以我查看了解决方案代码,他们已经注释掉了构造函数,所以这就是我所做的并且工作正常。这给我留下了三个问题...
- 我认为子类将自动继承其父类(super class)的构造函数(如果未在子类中定义)的想法是否正确?当我将其注释掉时,情况似乎就是这样。
- 我在
TitleTrigger()
中使用的构造函数与其父类(super class)WordTrigger()
中的构造函数完全相同,所以我是否定义它有什么关系在子类中还是允许子类继承? - 我还有另外两个
WordTrigger()
的子类,它们与TitleTrigger()
相同,除了一个在故事主题中查找单词,另一个在概括。这两个通过他们自己的构造函数测试得很好,这看起来真的很奇怪。
如果需要,我可以包含测试代码,但如果问题只是该代码如何测试我的类的一个怪癖,我真的不需要知道那个怪癖是什么。对于 future 的情况,我真正想知道的是,如果子类(子类)没有定义自己的构造函数,子类是否会自动继承它们的父类(super class)构造函数,有点像它们如何从父类(super class)继承其他方法。
最佳答案
Am I correct in thinking that subclasses will automatically inherit the constructor of their super-class if it's not defined in the subclass?
是的。 Java 中防止这种情况发生的问题是重载(即每个人都从 Object
继承,所以每个人最终都会得到一个 nullary 构造函数)。在 Python 中不是问题,所以我们可以继承构造函数。
The constructor I used in TitleTrigger() is an exact duplicate of the constructor in its super-class WordTrigger(), so why would it matter whether I defined it in the subclass or allowed the subclass to inherit it?
它不应该(除了为了减少代码重复),除非我遗漏了什么。
These two pass the tests just fine with their own constructors, which seems really bizarre.
是的。如果没有看到更多代码/错误,我无法猜测出了什么问题。此外,在这里使用类似乎有点矫枉过正——函数就可以了。不是 Java,所以我们不需要将所有东西都包装在无用的 OO 层中。
关于python - 构造函数在python中是否继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24333163/