简体   繁体   中英

Python classes and __init__ method

I am learning python via dive into python. Got few questions and unable to understand, even through the documentation.

1) BaseClass

2) InheritClass

What exactly happens when we assign a InheritClass instance to a variable, when the InheritClass doesn't contain an __init__ method and BaseClass does ?

  • Is the BaseClass __init__ method called automatically
  • Also, tell me other things that happen under the hood.

Actually the fileInfo.py example is giving me serious headache, i am just unable to understand as to how the things are working. Following

Yes, BaseClass.__init__ will be called automatically. Same goes for any other methods defined in the parent class but not the child class. Observe:

>>> class Parent(object):
...   def __init__(self):
...     print 'Parent.__init__'
...   def func(self, x):
...     print x
...
>>> class Child(Parent):
...   pass
...
>>> x = Child()
Parent.__init__
>>> x.func(1)
1

The child inherits its parent's methods. It can override them, but it doesn't have to.

@FogleBird has already answered your question, but I wanted to add something and can't comment on his post:

You may also want to look at the super function . It's a way to call a parent's method from inside a child. It's helpful when you want to extend a method, for example:

class ParentClass(object):
    def __init__(self, x):
        self.x = x

class ChildClass(ParentClass):
    def __init__(self, x, y):
        self.y = y
        super(ChildClass, self).__init__(x)

This can of course encompass methods that are a lot more complicated, not the __init__ method or even a method by the same name!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM