explicit call to __init__(self) in subclass needed?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Sep 18 11:06:07 CEST 2009


Andrew MacKeith a écrit :
> I create a class like this in Python-2.6
> 
>  >>> class Y(str):
> ...   def __init__(self, s):
> ...      pass
> ...
>  >>> y = Y('giraffe')
>  >>> y
> 'giraffe'
>  >>>
> 
> How does the base class (str) get initialized with the value passed to 
> Y.__init__() ?

It happens in the __new__ method (which is the proper "constructor")

class Y(str):
     def __new__(cls, value, foo="foo"):
         instance = str.__new__(cls, value)
         instance.foo = foo
         return instance

     def __repr__(self):
         return "<%s(%s, %s)>" % (type(self).__name__, self, self.foo)


> Is this behavior specific to the str type,  or do base classes not need
> to be explicitly initialized?

When you override a method in a derived class, it's your responsability 
to call on the parent(s) class(es) implementation. __init__ is not an 
exception to that rule. The point is that since __init__ works by 
mutating the newly created instance, it makes no sense to have a 
distinct __init__ for immutable types - which have their "value" set 
once for all at creation time.



More information about the Python-list mailing list