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 ?
__init__
method called automaticallyActually the fileInfo.py example is giving me serious headache, i am just unable to understand as to how the things are working. Following
In order to access object attributes from within the __init__ method we need a reference to the object. Whenever a method is called, a reference to the main object is passed as the first argument. By convention you always call this first argument to your methods self.
The __init__ method is a special method of a class. It is also called the constructor method and it is called when we create (instantiate) an object of the class. We use the __init__ method to initialise class attributes or call class methods.
"__init__" is a reseved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.
__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With