About the Python callable object A good article, can't help copy come over, respect the author original, quote as follows:
Http://www.jianshu.com/p/a96e71ff7f07
There is an interesting syntax in Python, as long as the type is defined , the call function is implemented, and the type becomes callable.
In other words, we can use this type of object as a function, equivalent to overloading the bracket operator.
For example, now we want to calculate the natural fall displacement in the gravity environment. We know Sy= (gt**2)/2, then we can build a function:
def g_dpm (t): Return
(9.8*t**2)/2
As we all know, the gravitational acceleration of the Earth's surface is about equal to 9.8m/s**2, and this function is really not technically content.
Slow, the boss said, I want to calculate is Mars ah ¥%#.
Uh...... Can you say that others are unreasonable? In EA's FIFA football, I've seen microgravity-mode pitches, but in a computer program, a lot of surreal needs are possible.
Well, the easiest way of course is:
def mar_g_dpm (t): Return
(3.92*t**2)/2 #火星表面的重力加速度约等于地球表面的2/5
However, you can really guarantee that the next cute plan will not design a Venus scene. or Jupiter. Or the Damned Great Wizard Guild begins to sell a new magic scroll--gravity control.
Of course, we can design this function like this:
Def G_DPM (g, T): Return
(g*t**2)/2
But G is a much more stable quantity than t, and basically, in a single correlation operation, G can be used as a constant. Then, a callable object might be more appropriate. The following defines such a type:
Class G_DPM (object):
def __init__ (Self, g):
self.g = g
def __call__ (self, T): Return
(self.g*t**2)/2
When we calculate the earth scene, we can make
E_DPM = G_DPM (9.8), s = E_DPM (t).
In the same way, it's easy to generate free landing formulas in other gravity environments.
We need to determine if the objects in Python can be invoked, and we can use the built-in method Python callable ()
Returns true if the object can be invoked, or false if the object cannot be invoked.