(100 days, 2 hours, fourth day) The role of _init_() method

1. Why must the _init_() method be defined? Let’s take a look at the difference between definition and undefined:

1.c is an instantiated object of C, if there is an _init_() method, call C first.

class A:
    def __init__(self):
        print("math")
class B:
    def __init__(self):
        print("hello")
class C(A,B):
    def __init__(self):
        print("world")
    def get(self):
        print("得到方法")

c=C()  #注意括号,要记得加括号,实例化时就会调用本身的方法

  

2. C is an instantiated object of C, if there is no _init_() method in C to call the parent class.

  If C(A,B) then call A, if C(B,A) then call B

class A:
    def __init__(self):
        print("math")
class B:
    def __init__(self):
        print("hello")
class C(A,B):
    #def __init__(self):
       # print("world")
    def get(self):
        print("得到方法")

c=C()  #注意括号,要记得加括号,实例化时就会调用本身的方法

 

3. If there is no such function in A, B, C, there is no output.

class A:
    def a(self):
        print("math")
class B:
    def b(self):
        print("hello")
class C(A,B):
    #def __init__(self):
       # print("world")
    def get(self):
        print("得到方法")

c=C()  #注意括号,要记得加括号,实例化时就会调用本身的方法
print('都没有')

  

4. The __init__() function in the class is called the constructor, also called the constructor, or the initialization function. Its function is to initialize the default value of the passed instance when initializing the instance. If you don't write __init__(), the default empty __init__() will be called. To put it bluntly, this method will be called no matter whether you write it or not, and it will be called once it is instantiated.

Note: __init__There are two underscores before and after " "! ! !

Note that __init__the first parameter of the method is always self, which represents the created instance itself. Therefore, within the __init__method, various properties can be bound to self, because self points to the created instance itself.

With a __init__method, when creating an instance, you cannot pass in empty parameters. You must pass __init__in parameters that match the method, but self does not need to be passed .

class Student():
    def __init__(self, name, score):
        self.name=name
        self.score=score

bart = Student('Bart Simpson', 59)
print(bart.name)
print(bart.score)

 

Compared with ordinary functions, the functions defined in the class are only different, that is, the first parameter is always the instance variable self, and there is no need to pass this parameter when calling.

Guess you like

Origin blog.csdn.net/zhangxue1232/article/details/109367105