Parent calls the subclass method

python and other object-oriented languages ​​Similarly, each class can have one or more base classes that inherit properties and methods from the parent class there. If a method is called in the instance of the subclass, or a property is accessed at the instance of the subclass, but the method or property does not exist in the subclass, it will automatically go to class to find his father.

After inheriting the parent class, you can call the parent class methods and properties to access the parent class, and to complete the integration process, is a subclass constructor you want to call.

Subclass does not explicitly call the constructor of the parent class, and parent class constructor initializes some properties, there will be problems

If the child class and parent class has a constructor, in fact, it is a subclass overrides the constructor of the parent class, if you do not explicitly call the parent class constructor, the constructor of the parent class will not be executed, resulting in sub-class instance access the parent class initialization method in initial variables will be a problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class  A:
     def __init__(self):
         self.namea= "aaa"
  
     def funca(self):
         print( "function a : %s" %self.namea)
  
class  B(A):
     def __init__(self):
         self.nameb= "bbb"
  
     def funcb(self):
         print( "function b : %s" %self.nameb)
  
b=B()
print(b.nameb)
b.funcb()
  
b.funca()

 

 result:

1
2
3
4
5
6
7
8
bbb
function b : bbb
Traceback (most recent call last):
   File  "/home/lai/workspace/sru/2.py" , line 24,  in  <module>
     b.funca()
   File  "/home/lai/workspace/sru/2.py" , line 11,  in  funca
     print( "function a : %s" %self.namea)
AttributeError:  'B'  object  has no attribute  'namea'

In a subclass, the constructor is rewritten, but the new construction method namea no code on the properties of the parent class initialization, in order to achieve the desired effect, the configuration of subclass must call the constructor of the superclass be substantially initialization. There are two ways to achieve this goal: Unbound version call the superclass constructor, or use super function.

Method One: call the superclass constructor unbound

Modify the code by more than one line:

class A:
    def __init__(self):
        self.namea="aaa"
 
    def funca(self):
        print("function a : %s"%self.namea)
 
class B(A):
    def __init__(self):
        self.nameb="bbb"
        #这一行解决了问题
        A.__init__(self)
    def funcb(self):
        print("function b : %s"%self.nameb)
 
b=B()
print(b.nameb)
b.funcb()
 
b.funca()

 result

1
2
3
bbb
function b : bbb
function a : aaa

 

As annotated line to solve the problem, the direct use of the name of the parent class to call its constructor.

This method is called constructor unbound call the parent class. When calling an instance method, self parameters of the method are automatically bound to instances (called a binding method). But if the method (such as A .__ init) directly call the class, then there is no instance is binding. This will provide a free self required parameters, this method is called unbound method is not binding.

By the present example, as to a method for providing self unbound parameter, B can use all the parent class constructor implemented so namea variable is set.

Method two: the super function

Modify the code, the need to add two lines to increase in the original Code:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#父类需要继承object对象
class  A( object ):
     def __init__(self):
         self.namea= "aaa"
  
     def funca(self):
         print( "function a : %s" %self.namea)
  
class  B(A):
     def __init__(self):
         #这一行解决问题
         super(B,self).__init__()
         self.nameb= "bbb"
  
     def funcb(self):
         print( "function b : %s" %self.nameb)
  
b=B()
print(b.nameb)
b.funcb()
  
b.funca()

 Results with the same method

1
2
3
bbb
function b : bbb
function a : aaa

 

As for the new annotated code, which allows the first sentence of the object class inherits from class A, in order to use super function, because this is the python "new class" features supported. The current mine and objects can be used as parameters super function, any method invocation function returns an object of the superclass are called instead of the method of the current class.

super function returns a super object that is responsible for analytical methods, analytical process that will automatically find the parent of all of the parent and the parent class.

 A more intuitive method, a second method can initialize all its superclasses

super function more intuitive than in super tired directly call unbound method, but the biggest is a little more if the child class inherits the parent class, it only requires the use of a super function can be. But without this requirement, the direct use A .__ init __ (self) more intuitive.

 

The parent can call the subclass of it?

● 把子类传递到父类的有参构造中,然后调用。
● 使用反射的方式调用,你使用了反射还有谁不能调用的?!
● 父类调用子类的静态方法。

案例展示:

package com.ywq;



public class Test2{
public static void main(String[] args)
{
Son son = new Son();
Father father=new Father(son);
father.fun1();
father.fun4();
}
}
class Father{
public Son son;
public Father(Son son){
this.son=son;
}
public Father() {

}

public void fun4(){
//方法3:使用反射的方式调用子类方法
try {
Class cls=Class.forName("com.ywq.Son");
Son son=(Son) cls.newInstance();
son.fun2();
} catch (Exception e) {

e.printStackTrace();
}
}
public void fun1(){
//方法1:把子类传递到父类的有参构造函数中,然后调用。
System.out.println("我是父类的方法");
son.fun2();

//方法2:父类调用子类的静态方法。
Son.fun3();
}
}

class Son extends Father{

public static void fun3(){
System.out.println("我是子类的静态方法");
}
public void fun2(){
System.out.println("我是子类的方法");

}

}
这三种都是父类直接调用子类的方法,
参考:https://blog.csdn.net/oschina_41675984/article/details/80373587

Guess you like

Origin www.cnblogs.com/klb561/p/11361586.html