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 python uses classes to implement decorators

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

Share

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

This article mainly introduces python how to use classes to achieve the decorator, the article introduces in great detail, has a certain reference value, interested friends must read!

Try to use classes to implement decorators

Most decorators are based on functions and closures, but this is not the only way to make decorators. In fact, Python has only one requirement as to whether an object can be used in the form of a decorator (@ decorator): decorator must be an object that can be called (callable).

# use callable to detect whether an object is callable > > def foo (): pass... > > type (foo) > callable (foo) True

Functions are naturally "callable" objects. But in addition to functions, we can also make any class "callable". The solution is simple, just customize the _ _ call__ magic method of the class.

Class Foo: def _ _ call__ (self): print ("Hello, _ _ call___") foo = Foo () # OUTPUT: Trueprint (callable (foo)) # call foo instance # OUTPUT: Hello, _ _ call__foo ()

Based on this feature, we can easily use classes to implement decorators.

The following code defines a decorator called @ delay (duration) that uses the decorated function to wait for an extra duration second before each execution. At the same time, we also want to provide users with an eager_call interface that does not need to wait for immediate execution.

Import timeimport functoolsclass DelayFunc: def _ init__ (self, duration, func): self.duration = duration self.func = funcdef _ _ call__ (self, * args, * * kwargs): print (f'Wait for {self.duration} seconds...') Time.sleep (self.duration) return self.func (* args, * * kwargs) def eager_call (self, * args, * * kwargs): print ('Call without delay') return self.func (* args, * * kwargs) def delay (duration): decorator: delay the execution of a function. It also provides the .eager _ call method to execute immediately "" # here to avoid defining additional functions Directly use functools.partial to help construct # DelayFunc instance return functools.partial (DelayFunc, duration) sample code of how to use the decorator: @ delay (duration=2) def add (a, b): return a + b # this call will be delayed by 2 seconds add (1,2) # this call will execute add.eager_call (1,2) immediately

@ delay (duration) is a class-based decorator. Of course, if you are familiar with functions and closures in Python, the above delay decorator can be implemented only with functions. So, why do we use classes to do this?

Compared with pure functions, I think a decorator implemented by a class has several advantages in a particular scenario:

When implementing a stateful decorator, the attributes of the action class are more intuitive and less error-prone than the variables in the operation closure.

When implementing a decorator as a function extension interface, using classes to wrap functions is easier to maintain than directly appending attributes to function objects.

It is easier to implement an object that is compatible with both decorator and context manager protocols.

These are all the contents of the article "how python uses classes to implement decorators". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

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

Development

Wechat

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

12
Report