In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how python uses namedtuple and dataclass to define a class, which has a certain reference value, and interested friends can refer to it. I hope you can learn a lot after reading this article.
Classes with simple functions are defined using namedtuple and dataclass
Sometimes when we want to implement a class-like function, but there are less complex methods to operate, we can consider the following two methods.
The first, namedtuple, is also called a named tuple, a tuple with a name. As a module in the Python standard library collections, it can achieve a function similar to a class.
From collections import namedtuple# previously simple classes can be implemented using namedtuple. Car = namedtuple ('Car',' color mileage') my_car = Car ('red', 3812.4) print (my_car.color) print (my_car)
However, all the attributes need to be defined in advance before they can be used. For example, if you want to use my_car.name, you have to change the code to look like this.
From collections import namedtuple# previously simple classes can be implemented using namedtuple. Car = namedtuple ('Car',' color mileage name') my_car = Car ('red', 3812.4, "Auto") print (my_car.color) print (my_car.name)
The disadvantages of using namedtuple are obvious.
So now the better solution is to add Python3.7 to the dataclass of the standard library.
In fact, it can also be used in 3.6, but it needs to be used as a third-party library, it can be installed using pip.
Examples of use are as follows:
From dataclasses import dataclass@dataclassclass Car: color: str mileage: floatmy_car = Car ('red', 3812.4) print (my_car.color) print (my_car) Thank you for reading this article carefully. I hope the article "how python defines a class using namedtuple and dataclass" shared by the editor will be helpful to you. At the same time, I hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.