How to call subclass methods in a superclass in Python

I want to know how to call subclass methods in a superclass.

+6
source share
5 answers

The point behind the subclass is that it extends and modifies the behavior of the superclass. The superclass cannot know how the subclass will expand it.

Edit: But it is possible that the superclass knows that the subclass will extend it. Not sure, although it's a good design.

+9
source

I believe this is a commonly used pattern.

class A(object): def x(self): self.y() def y(self): print('default behavior') class B(A): def y(self): print('Child B behavior') class C(A): def z(self): pass >>>B().x() Child B behavior >>>C().x() default behavior 

This is similar to an abstract class, but provides default behavior. It is impossible to remember the name of the pattern from the top of the head.

+7
source

This is a very broad question. Since you do not provide sample code, I will just show the simplest example:

 class A(object): def meth1(self, a): self.meth2(a, a*a) class B(A): def meth2(self, a, b): return b / a b = B() b.meth1(10) 
+2
source

Here is what I just tried:

 class A(object): def x(self): print self.y() class B(A): def y(self): return 1 >>> B().x() 1 

So, if you didn't have any specific problem, just call the method from a subclass in the base class, and it should just work.

0
source

I think this is due to the use of abstract methods. The parent class defines the methods that the subclass must execute, and the parent class knows that these methods will be implemented. Similar structures exist, for example, in Java.

Using these functions in Python is well discussed here: Abstract Methods in Python

0
source

Source: https://habr.com/ru/post/907551/


All Articles