Example of the _ call _ method in python: python _ call _
This article describes the usage of the _ call _ method in python and shares it with you for your reference. The specific method is analyzed as follows:
In Python, _ call _ allows programmers to create callable objects (instances). By default, the _ call _ () method is not implemented, this means that most instances cannot be called. However, if this method is overwritten in the class definition, the instance of this class will become callable.
The test. py file is as follows:
#!/usr/bin/python# Filename:test.py class CallTest(): def __init__(self): print 'init' def __call__(self): print 'call' call_test = CallTest()
Execution result:
_ Call __:
>>> from test import CallTestinit>>> t = CallTest()init>>> callable(t)False>>> t()Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: CallTest instance has no __call__ method>>>
Override _ call __:
>>> from test import CallTestinit>>> t = CallTest()init>>> callable(t)True>>> t()call>>>
I hope this article will help you with Python programming.
Python. When I define a function and Call it, I have an error.
Return op (a, B)
Change
Return op
Try
How does a subclass in Python call the parent class method?
As mentioned in the previous article, the class initialization method in python is _ init _ (). Therefore, this is the initialization method of the parent class subclass. If the subclass does not implement this function, the initialization function of the parent class is called during initialization. If the subclass implements this function, it overwrites the function of the parent class. Since it inherits the parent class, it is necessary to explicitly call the _ init _ () of the parent class in this function, which is different from C ++ and jAVA. They automatically call the parent class initialization function.
The following methods are used to call A parent class function: class A: def method (self, arg): pass
Class B ():
Def method (self, arg ):
# A. method (self, arg) #1
# Super (B, self). method (arg) #2
Super (). method (arg) #3
1. directly write the class name for calling
2. Use the super (type, obj). method (arg) method to call.
3. Call the parent class method of this class in the class definition, you can directly
Super (). method (arg ).
Example of calling the method of the object's parent class in code: ob = B () super (B, ob ). method (arg) # Call the method of class A, the parent class of class B.
Example of calling the parent class initialization method during initialization:
Class B ():