_init_() method in Python

Detailed interpretation of the __init__() method in Python

Notes on the __init__ method in Python

Summary of several methods of python's __init__

Explain in detail __init__ and __new__ in Python

 

The __new__ method is a method of creating a class instance , called when an object is created, and returns an instance of the current object

The __init__ method is called after the class instance is created , some initialization of the current object instance, no return value

 

Note 1. __init__ is not equivalent to the constructor in C#. When it is executed, the instance has been constructed.

class A(object):
    def __init__(self,name):
        self.name=name
    def getName(self):
        return 'A '+self.name

 when we execute

 

a=A('hello')

, can be understood as

a=object.__new__(A)
A.__init__(a,'hello')

 That is, the role of __init__ is to initialize the instantiated object.

 

Note 2. The subclass can not rewrite __init__. When instantiating the subclass,the __init__ defined in the superclass will be automatically called

class B(A):
    def getName(self):
        return 'B '+self.name
 
if __name__=='__main__':
    b=B('hello')
    print b.getName()

 

But if __init__ is overridden , when instantiating a subclass, it will not implicitly call the __init__ defined in the superclass

class C(A):
    def __init__(self):
        pass
    def getName(self):
        return 'C '+self.name
 
if __name__=='__main__':
    c=C()
    print c.getName()

 

It will report "AttributeError: 'C' object has no attribute 'name'" error, so if __init__ is overridden, in order to use or extend the behavior in the superclass, it is best to explicitly call the superclass's __init__ method

class C(A):
    def __init__(self,name):
        super(C,self).__init__(name)
    def getName(self):
        return 'C '+self.name
 
if __name__=='__main__':
    c=C('hello')    
    print c.getName()

 

。。。

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326479855&siteId=291194637