Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the _ _ call__ () method in python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to use the _ _ call__ () method in python. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

_ _ call__

In Python, a function is actually an object:

> f = abs > f.

Because f can be called, f is called a callable object.

All functions are callable objects.

An instance of a class can also become a callable object by implementing a special method _ _ call__ ().

We make the Person class a callable object:

Class Person (object): def _ init__ (self, name, gender): self.name = name self.gender = gender def _ call__ (self, friend): print'My name is% s..% self.name print'My friend is% s..% friend

You can now call directly on the Person instance:

> p = Person ('Bob',' male') > p ('Tim') My name is Bob...My friend is Tim...

Just looking at p ('Tim') you can't determine whether p is a function or an instance of a class, so in Python, a function is also an object, and the difference between an object and a function is not significant.

Task

Improve the Fibonacci series defined earlier:

Class Fib (object):

???

Add a _ _ call__ method to make the call easier:

> f = Fib () > > print f (10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] about how to use the _ _ call__ () method in python is shared here. I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report