Some method analysis of classes in python
- 2020-04-02 14:06:46
- OfStack
This article analyzes some methods of python classes as examples and shares them with you for your reference. Specific analysis is as follows:
Take a look at the following code:
class Super:
def delegate(self):
self.action()
class Provider(Super):
def action(self):
print 'in Provider.action'
x = Provider()
x.delegate()
The example running environment in this paper is Python2.7.6
The operation results are as follows:
In the Provider. The action
Define the delegate() method in the Super class, call self.action in the delegate, and implement the action method in the Provider subclass. When a subclass calls the parent class's delegate method, it actually calls its own action method.
In a word:
Here the subclass implements the desired action method in the parent delegate
Take a look at the following code:
class Super:
def delegate(self):
self.action()
def method(self):
print 'super method'
class Inherit(Super):
pass
class Replace(Super):
def method(self):
print "replace method"
class Extended(Super):
def method(self):
print 'in extended class'
Super.method(self)
print 'out extended class'
class Provider(Super):
def action(self):
print 'in Provider.action'
x = Inherit()
x.method()
print '*'*50
y = Replace()
y.method()
print '*'*50
z = Extended()
z.method()
print '*'*50
x = Provider()
x.delegate()
The operation results are as follows:
super method
**************************************************
replace method
**************************************************
in extended class
super method
out extended class
**************************************************
in Provider.action
Inherit the methods of the parent class, replace the methods of the parent class, extend the methods of the parent class
The Super class defines the delegate method and expects the subclass to implement the action function, while the Provider subclass implements the action method.
I believe that this article has a certain reference value for everyone to learn Python programming.