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 improve the efficiency of object-oriented programming with attrs in Python

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you how attrs in Python to improve the efficiency of object-oriented programming, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Foreword:

Python is an object-oriented language. Generally speaking, the use of object-oriented programming will make the development more efficient, the software quality better, and the code easier to expand, readable and maintainable. But if in a larger project, if there are a lot of entity classes and have very complex properties, you will gradually find Python classes really "tiring" to write. Why do you say that? take a look at the following Box class, whose properties are length, width, and hight:

Class Box: def _ _ init__ (self, length, width, hight): self.length = length self.width = width self.hight = hight

There is no problem in this way, and it is written in accordance with the Python specification. Every parameter in the initialization function needs to be assigned with self.xxx = xxx, and it is good to have fewer parameters, but if there are too many parameters, only the parameter assignment operation is enough to write for a while, if there are many classes in a project, then you really want to be numb.

And we know that in Python, when you want to customize the printout of the object itself, you need to implement the _ _ repr__ () method in its class, for example:

Def _ repr__ (self): return'{} (length= {}, width= {}, hight= {}) '.format (self.__class__.__name__, self.length, self.width, self.hight)

The _ _ repr__ () method is implemented so that our custom characters are output only when we print the object itself.

Box = Box (20,15,15) print (box) # the result output is Box (length=20, width=15, hight=15)

But sometimes because of the hassle, we don't want to implement the _ _ repr__ () method, but it's not friendly to print the results, so we get caught up in it.

If we want to compare objects and sometimes need to judge whether two objects are equal or relatively large, we need to implement various methods such as _ _ eq__ (), _ _ lt__ (), _ _ gt__ () and so on to compare objects, for example:

Def _ eq__ (self, other): if not isinstance (other, self.__class__): return NotImplemented return (self.length, self.width, self.hight) = (other.length, other.width, other.hight)

So we need to implement these methods for comparison. For example, if we have implemented all the methods mentioned above, and then suddenly add a property firmness hardness, then the methods of the whole class need to be modified, which is very excruciating. So is there a way to automatically add something similar to the one mentioned above when you create a class? the answer is yes, and that is the attrs module that we will introduce next, which can help us to easily define the class.

1. The use of attrs

We can use pip install attrs for installation.

Then modify the above code:

From attr import attrs, attrib@attrsclass Box: length = attrib (type=int, default=0) width = attrib (type=int, default=0) hight = attrib (type=int, default=0) box1 = Box (20,15,15) print (box1) box2 = Box (30,20,20) print (box2 = = box1) print (box2 > box1)

The Box class is decorated with the attrs within the module, and all the properties are defined using attrib, while specifying the type and default value of the property. And we didn't implement any of the methods mentioned above, but we did implement all the functions. Now if we add an attribute color color, which does not participate in the comparison of objects, but needs to output when printing, add an attribute hardness of firmness, which participates in the comparison of objects, but does not output when printing objects, it is very simple:

From attr import attrs, attrib@attrsclass Box: length = attrib (type=int, default=0) width = attrib (type=int, default=0) hight = attrib (type=int, default=0) color = attrib (repr=True, cmp=False, default= (0,0,0) hardness = attrib (repr=False, cmp=True, default=0) box1 = Box (20,15,15, (255,255,255), 80) print ("box1:", box1) box2 = Box (20,15,15,255,255,0) print ("box2:" Box2) print (box2 = = box1) print (box2 > box1)

The execution result is:

In other words, if we use the attrs library, it will make the definition of the class efficient and concise, eliminating the need to write redundant and complex code. For attrib (), receive the following parameters:

Default: the default value of the property. If no initialization data is passed in, the default value will be used.

Validator: validator to check whether the passed parameters are valid

Repr: whether or not to participate in the output of object printing

Cmp: whether to participate in object comparison or not

Hash: whether to remove the weight

Init: whether to participate in initialization. If False, this parameter cannot be used as the initialization parameter of the class. Default is True.

Metadata: metadata, read-only additional data

Type: type, such as int, str and other types. Default is None.

Converter: converter, perform some value processing and converter to increase fault tolerance

Kw_only: whether it is a mandatory keyword parameter. Default is False.

Here we only focus on validators and converters, the other parameters are easy to understand.

2. Verifier

Sometimes when setting a property, we have to meet certain conditions, such as the above color color attribute, we use RGB tricolor mode, such as black is (255255255), for this case, we need to verify that the attribute is legal.

For example:

Def color_is_valid (instance, attr, value): if not isinstance (value, set): raise ValueError (f "Parameter {attr.name}: {value} is invalid!") For i in value: if not 0

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