Python对象定义

时间:2013-01-15 16:16:44

标签: python oop object instantiation

这应该很容易,但因为我遗漏了一些东西。

我有一个完全按照我的预期工作的对象。

class TextElement(ContentItemElement):
    '''
    Single String Elements, for example, headlines
    '''
    def __init__(self, name, data):
       super(TextElement, self).__init__()
       self.name=name
       self.text=data


    def prettyPrint(self):
        printstring =  u'*HTML* '
        self.name.encode('utf-8')
        printstring += u'<h3> '+self.name+u' </h3>'
        self.text.encode('utf-8')
        printstring += u'<p> '+self.text+u' </h3>'
        print printstring 

好的,很好,我可以实例化它,它完全符合我的要求。但我真的想创建一个更具体的TextObjects版本。所以我这样做:

class CiteElement(TextElement):
    '''
    Single String Elements, for example, headlines
    '''
    def __init__(self, name, data):
        super(CiteElement, self).__init__()
        self.validValues=['Crap I make up', 'Crap I found on the web']

但是当我尝试实例化它时,这有效:

ee = TextElement(element, self.raw[element])
ee.validValues=['Crap I make up', 'Crap I found on the web']

但这不是

ee = CiteElement(element, self.raw[element])

反而给我这个错误:

TypeError: __init__() takes exactly 3 arguments (1 given)

显然我错过了一些小事。 python对象的关键。我应该知道的东西,但已经编写了多年。但它是什么?

2 个答案:

答案 0 :(得分:6)

这一行

super(CiteElement, self).__init__()

应该是

super(CiteElement, self).__init__(name, data)

答案 1 :(得分:3)

因为基类的构造函数定义为

def __init__(self, name, data):
....

你在没有派生类的参数的情况下调用它。

def __init__(self, name, data):
    super(CiteElement, self).__init__()