Python 3.7: Introduction to Data Classes __python

Source: Internet
Author: User


Python3.7 is expected to release this summer, let's take a peek at the new features it brings. If you often use a pycharm code at home, be sure to upgrade your pycharm to version 2018.1. (wait until you finish reading this article and then upgrade it too late).

The Python3.7 version contains a number of new features, such as upgrades to various character sets, delaying evaluation of annotations, and so on. One of the most anticipated new features is support for data class adorners.

What is a data class

Most Python developers have written many classes, such as the following image.  


Data classes can automatically generate "magic" methods for your defined instances. For example, __init__ can receive parameters and assign arguments to self. The small example in the previous illustration can also be written like this:

The key difference is that the data class is actually asking for type hints. If you've never used a type hint before: A type hint allows you to mark which data type a variable in your code should be. At run time, the data type of the variable is not checked, but you can check your code statically with pycharm or command-line tools such as Mypy.

So, let's see how to use this new feature.

Star Wars API

You must know that when a movie fan creates a group rest API with the data of his favorite movie, the fans of the movie will respond enthusiastically. That's what a Star Wars fan did, creating the Star Wars API. In fact, he did a better job of creating a Python library directly for the API.

Let's take a moment to forget about the existence of this wrapper and explore how to create our own library.

We can use the request library to get resources from the Star Wars API.

This terminal (like all terminals) responds with JSON-formatted information. The request library also provides JSON parsing.

At this point we put the data into a dictionary, let's take a look.


Encapsulate This API

To properly encapsulate this API, we should create an object that users can use in their own applications. So let's use Python3.6 to define an object that holds the response to the/films/terminal request.

Attentive readers may have noticed that the above code has some redundancy, and less attentive readers can refer to the complete Python3.6 implementation (but not short).

This is a classic example of a data class decorator that helps you get out of trouble. We created a class to hold the data for a small amount of validation. Let's take a look at some of the areas that need to be modified.

First, the data class automatically generates some magic methods. If we do not specify any options for the data class adorner, the automatically generated magic method is: __init__,__eq__, and __repr__. If you and the definition of __repr__, not __str__, then Python will default to the implementation of __STR__ To return the output of the __repr__. In turn, you can get four magic methods by modifying the code as follows:

Here we remove the __init__ method to ensure that the data class adorner can add a subset of it. Unfortunately, in this step, we are missing a feature. Our Python3.6 constructor not only defines all the values, but it should also try to parse the data. How do we use data classes to implement this functionality?

If we rewrite the __init__ method, we lose the benefit of using the data class. Therefore, in order to achieve these additional processing, a new magic method __post_init__ was born. Let's see what this method looks like in the object we're encapsulating:

With the help of the data class decorator, we implemented our class with just 1/3 lines of code.

more of the benefits

By using the adorner's options, you can further customize the data class for your own instance. The default option is this:

The INIT option determines whether the __init__ method is generated.

The REPR option determines whether the __repr__ method is generated.

The EQ option Ibid, where the __eq__ method defines an operation that checks for equality.

The order option actually generates four magic methods to define the check for greater than, less than, and, or operations, and you can sort the objects by setting this to true.

The last two options determine whether your object can be hashed. This is necessary, for example, when you want to use the object of a class as a dictionary key. The hash function should be in effect for the life of the object, otherwise the dictionary storing the data will no longer be able to find your object. The __HASH__ function in the data class will return the hash value of all objects in the data class by default. Therefore, the __HASH__ function is generated by default only when you set the object to be read-only (frozen=true).

Once the read-only property is set with Frozen=true, any write to your object will be an error. If you think this is too harsh and still want to make sure the object is never changed, you can set unsafe_hash=true instead of Frozen=true. Developers of data class adorners do not recommend doing this.

If you want to get a deeper understanding of the data class, you can look up the PEP or start playing with the data class directly. Please tell us in the comments what you have done with the data class.


∞∞∞∞∞



The IT faction-{Technical Youth Circle} continues to focus on the Internet, block chains, AI fields



Public number back to "Python",

Invite you to join the {It sent Python technology Group}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.