Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

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

Shulou Source: shulou.com Published: 2022-06-02 07:12:30 09月23日 Update

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.

Tags: Object function method adjustable instance content article more knowledge article good significant special task sequence quality or reference help related Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Xiaomi macOS Shulou Technology Microsoft