python - Am I using super() correctly? -
i made small chunk of code because i'm still trying figure out specifics of using super()
. why chunk run typeerror
?
= secondclass() typeerror: __init__() takes 2 arguments (1 given)
then, secondclass.meth()
function supposed print string, i'm missing conceptually.
class firstclass (object): def __init__ (self, value): self.value = value print self.value class secondclass (firstclass): def meth (self): super (firstclass,self).__init__(value = "i strange string") = secondclass() a.meth()
this isn't super
. don't define __init__
secondclass
explicitly - but, because inherits firstclass
, inherits firstclass
's __init__
. can't instantiate object without passing in value
parameter.
edit ok. first point, others have mentioned, must use current class in super call, not superclass - in case super(secondclass, self)
. that's because super means "get parent of class x", mean "get parent of secondclass" - firstclass.
the second point doesn't make sense call __init__
method inside meth
. __init__
already called when instantiate object. either subclass defines own version, can choose whether or not call own super method; or, in case, doesn't, in case superclass's version called automatically.
let me repeat that, because suspect missing piece in understanding: whole point of subclassing don't override, gets inherited anyway. super
only cases when want override something, still use logic super class as well.
so here's silly example:
class firstclass(object): def __init__ (self, value="i value firstclass"): print value def meth(self): print "i meth firstclass" def meth2(self): print "i meth2 firstclass" class secondclass(firstclass): def __init__ (self): print "i in secondclass" super(secondclass, self).__init__(value="i value secondclass") def meth(self): print "i meth secondclass" a=firstclass() # prints "i value firstclass" b=secondclass() # prints *both* "i in secondclass" *and* "i value secondclass a.meth() # prints "i meth firstclass" b.meth() # prints "i meth secondclass" a.meth2() # prints "i meth2 firstclass" b.meth2() # *also* prints "i meth2 firstclass", because didn't redefine it.
Comments
Post a Comment