In Python, the _ call _ function is interesting.
This article mainly introduces the interesting function _ call _ in Python. This article provides an example to explain the usage of the _ call _ function, for more information, see
There is an interesting syntax in Python. This type becomes callable when the _ call _ function is implemented when the type is defined.
In other words, we can use this type of object as a function, which is equivalent to overloading the brackets operator.
?
1 2 3 4 5 |
Class g_dpm (object ): Def _ init _ (self, g ): Self. g = g Def _ call _ (self, t ): Return (self. g * t ** 2)/2 |
When computing Earth scenarios, we can set e_dpm = g_dpm (9.8), s = e_dpm (t ).
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
Class Animal (object ): Def _ init _ (self, name, legs ): Self. name = name Self. legs = legs Self. stomach = [] Def _ call _ (self, food ): Self. stomach. append (food) Def poop (self ): If len (self. stomach)> 0: Return self. stomach. pop (0) Def _ str _ (self ): Return 'a animal named % s' % (self. name) Cow = Animal ('King', 4) # We make a cow Dog = Animal ('drop', 4) # We can make your animals Print 'we have 2 animales a cow name % s and dog named % s, both have % s legs '% (cow. name, dog. name, cow. legs) Print cow # here _ str _ metod work # We give food to cow Cow ('gras ') Print cow. stomach # We give food to dog Dog ('bone ') Dog ('beef ') Print dog. stomach # What comes inn most come out Print cow. poop () Print cow. stomach # Empty stomach ''' --> Output We have 2 animales a cow name king and dog named flopp, both have 4 legs A animal named king ['Gras '] ['Bione', 'beef '] Gras [] ''' |