In Python, the _ call _ function is interesting.

Source: Internet
Author: User

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

[]

'''

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.