Get the App
SLTechnology News&Howtos  ›  Development  › 

An example Analysis of the encapsulation process of python function

Shulou Source: shulou.com Published: 2022-06-03 15:34:04 10月29日 Update

This article will explain in detail the example analysis of the encapsulation process of python functions. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

1. Create a class called Function that can wrap any function and call it by overriding the _ _ call__ method.

It also provides a method called key, which returns a tuple so that the function is unique throughout the code base.

From inspect import getfullargspec class Function (object): "" Function class is an encapsulation of standard Python functions "" def _ init__ (self, fn): self.fn = fn def _ call__ (self, * args, * * kwargs): "when called like a function, it calls the encapsulated function. And return the return value of the function "" return self.fn (* args, * * kwargs) def key (self, args=None): "returns a key that uniquely identifies a function (even if it is overloaded)"# if args is not specified Then extract the parameter if args is None: args = getfullargspec (self.fn) .args return tuple ([self.fn.__module__, self.fn.__class__, self.fn.__name__, len (args or []),]) from the definition of the function.

2. Overriding the _ _ call__ method will call the encapsulated function and return the calculated value.

This causes the instance of Function to be called like a function, behaving exactly the same as the encapsulated function.

Def area (l, b): return l * b > > func = Function (area) > func.key () ('_ main__', 'area', 2) > func (3,4) 12 is here. I hope the above content can be helpful to you, so that you can learn more knowledge, if you think the article is good. Please share it for more people to see.

Tags: Functions encapsulation methods articles examples procedures analysis more good practical same code content parameters examples articles standards identifiers knowledge behavior Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple vpn Huawei Linux NVidia