Python's super() , what exactly happens? -


this question has answer here:

i trying understand objects created when instantiate child class in python, example:

class car():     def __init__(self, make, model, year):         self.make = make         self.model = model         self.year = year  class electriccar(car):      def __init__(self, make, model, year):           super().__init__(make, model, year)  my_tesla = electriccar('tesla', 'model s', 2016) 

when create object my_tesla, instantiate class electriccar calling constructor of class, in turn calls constructor of parent. how happen? right have 2 guesses:

1) super() reference parent class, call constructor of parent "super().init(make, model, year)" instantiating our child class. result have one object of our class electriccar().

2) super(), calls constructor of parent, create object of "car" class, call constructor of object, "super().init(make, model, year)". result have two objects: 1 object of class car() , 1 object of class electiriccar, in our case same though.

which 1 correct? if neither please explain happens in the:

 super().__init__(make, model, year) 

__init__ isn't constructor, it's initializer. time __init__ called, objects has been constructed (via __new__). 1 object, it's initialized twice - example, electriccar.__init__ may decide re-initialize self.model after car.__init__ has been run.

when calling super(), appropriate baseclass looked in context of current instance. basically, super().__init__(make, model, year) rewritten car.__init__(self, make, model, year) in example.

this why in earlier versions of python, call super(electriccar, self) - looks baseclass of current class (electriccar) , uses current instance (self) if instance of class instead.

note initializing doesn't mean preparing object, means preparing object's state. object functional when not implement __init__.


to clarify: when call electriccar(), executed close this:

that_object = electriccar.__new__()  # use object.__new__ if isinstance(that_object, electriccar):     electriccar.__init__(that_object) return that_object 

that means have one object call electriccar.__new__. call electriccar.__init__ modify/initialize object. may using other functions, such car.__init__.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -