Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using Data Classes in Python Show
Table of Contents
One new and exciting feature coming in Python 3.7 is the data class. A data class is a class typically containing mainly data, although there aren’t really any
restrictions. It is created using the new
A data class comes with basic functionality already implemented. For instance, you can instantiate, print, and compare data class instances straight out of the box: >>>
Compare that to a regular class. A minimal regular class would look something like this:
While this is not much more code to write, you can already see signs of the boilerplate pain:
>>>
Seems like data classes are helping us out behind the scenes. By default, data classes implement a
In this tutorial, you will learn exactly which conveniences data classes provide. In addition to nice representations and comparisons, you’ll see:
We will soon dive deeper into those features of data classes. However, you might be thinking that you have already seen something like this before. Alternatives to Data ClassesFor simple data structures, you have probably already used a >>>
It works. However, it puts a lot of responsibility on you as a programmer:
Furthermore, using these structures is not ideal: >>>
A better alternative is the
This definition of >>>
So why even bother with data classes? First of all, data classes come with many more features
than you have seen so far. At the same time, the >>>
While this might seem like a good thing, this lack of awareness about its own type can lead to subtle and hard-to-find bugs, especially since it will also happily compare two different >>>
The
>>>
Data classes will not replace all uses of Another alternative, and one of the inspirations for data classes, is the
This can be used in exactly the same way as the In addition to Basic Data ClassesLet us get back to data classes. As an example, we will create a
What makes this a data class is the Those few lines of code are all you need. The new class is ready for use: >>>
You can also create data classes similarly to how named tuples
are created. The following is (almost) equivalent to the definition of
A data class is a regular Python class. The only thing that sets it apart is that it has basic data model methods like Default ValuesIt is easy to add default values to the fields of your data class:
This works exactly as if you had specified the default values in the definition of the
>>>
Later you will learn about Type HintsSo far, we have not made a big fuss of the fact that data classes support typing out of the box. You have probably noticed that we defined the fields with a type hint: In fact, adding
some kind of type hint is mandatory when defining the fields in your data class. Without a type hint, the field will not be a part of the data class. However, if you do not want to add explicit types to your data class, use
While you need to add type hints in some form when using data classes, these types are not enforced at runtime. The following code runs without any problems: >>>
This is how typing in Python usually works: Python is and will always be a dynamically typed language. To actually catch type errors, type checkers like Mypy can be run on your source code. Adding MethodsYou already know that a data class is just a regular class. That means that you can freely add your own methods to a data class. As an example, let us calculate the distance between one position and another, along the Earth’s surface. One way to do this is by using the haversine formula: You can add a
It works as you would expect: >>>
More Flexible Data ClassesSo far, you have seen some of the basic features of the data class: it gives you some convenience methods, and you can still add default values and other methods. Now you will learn about some more advanced features like parameters to the Let us return to the playing card example you saw at the beginning of the tutorial and add a class containing a deck of cards while we are at it:
A simple deck containing only two cards can be created like this: >>>
Advanced Default ValuesSay that you want to give a default value to the
For fun, the four different suits are specified using their Unicode symbols.
To simplify comparisons of cards later, the ranks and suits are also listed in their usual order. >>>
In theory, you could now use this function to specify a default value for
Don’t do this! This introduces one of the most common anti-patterns in Python: using mutable default arguments. The problem is that all instances of Instead, data classes use something called a
The argument to >>>
The
In the The
The metadata (and other information about a field) can be retrieved using the >>>
You Need Representation?Recall that we can create decks of cards out of thin air: >>>
While this representation of a
Let us implement a user-friendly representation of a
The cards now look much nicer, but the deck is still as verbose as ever: >>>
To show that it is possible to add your own
Note the >>>
Comparing CardsIn many card games, cards are compared to each other. For instance in a typical trick taking game, the highest card takes the trick. As it is currently implemented, the >>>
This is, however, (seemingly) easy to rectify:
The
See the original PEP for more information about each parameter. After setting >>>
How are the two cards compared though? You have not specified how the ordering should be done, and for some reason Python seems to believe that a Queen is higher than an Ace… It turns out that data classes compare objects as if they were tuples of their fields. In other words, a Queen is higher than an Ace because >>>
That does not really work for us. Instead,
we need to define some kind of sort index that uses the order of >>>
For
Note that Finally, aces are high: >>>
You can now easily create a sorted deck: >>>
Or, if you don’t care about sorting, this is how you draw a random hand of 10 cards: >>>
Of course, you don’t need Immutable Data ClassesOne of the defining features of the
In a frozen data class, you can not assign values to the fields after creation: >>>
Be aware though that if your data class contains mutable fields, those might still change. This is true for all nested data structures in Python (see this video for further info):
Even though both >>>
To avoid this, make sure all fields of an immutable data class use immutable types (but remember that types are not enforced at runtime). The InheritanceYou can subclass data classes quite freely. As an example, we will extend our
In this simple example, everything works without a hitch: >>>
The
This code will immediately crash with a
However, this is not valid Python. If a parameter has a default value, all following parameters must also have a default value. In other words, if a field in a base class has a default value, then all new fields added in a subclass must have default values as well. Another thing to be aware of is how fields are ordered in a subclass. Starting with the base class, fields are ordered in the order in which they are first defined. If a field is redefined in a subclass, its order does not change. For example, if you define
Then the order of the fields in >>>
Optimizing Data ClassesI’m going to end this tutorial with a few words about slots. Slots can be used to make classes faster and use less memory. Data classes have no explicit syntax for working with slots, but the normal way of creating slots works for data classes as well. (They really are just regular classes!)
Essentially, slots are defined using The benefit of adding such restrictions is that certain optimizations may be done. For instance, slots classes take up less memory, as can be measured using Pympler: >>>
Similarly, slots classes are typically faster to work with. The following example measures the speed of attribute access on a slots data class and a regular data class using timeit from the standard library. >>>
In this particular example, the slot class is about 35% faster. Conclusion & Further ReadingData classes are one of the new features of Python 3.7. With data classes, you do not have to write boilerplate code to get proper initialization, representation, and comparisons for your objects. You have seen how to define your own data classes, as well as:
If you want to dive into all the details of data classes, have a look at PEP 557 as well as the discussions in the original GitHub repo. In addition, Raymond Hettinger’s PyCon 2018 talk Dataclasses: The code generator to end all code generators is well worth watching. If you do not yet have Python 3.7, there is also a data classes backport for Python 3.6. And now, go forth and write less code! Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using Data Classes in Python Apa itu Exception pada python?Assertions Exception adalah sebuah peristiwa, yang terjadi selama pelaksanaan program yang mengganggu aliran normal instruksi program. Secara umum, ketika skrip Python menemukan situasi yang tidak dapat diatasi, hal itu menimbulkan pengecualian. Exception adalah objek Python yang mewakili kesalahan.
Sebutkan apa saja yang bisa dilakukan untuk penanganan exception?Terdapat dua cara untuk menangani Exception yaitu dengan menangkap Exception dan melempar Exception.
Mengapa menggunakan Exception Handling?Exception Handling merupakan mekanisme yang paling diperlukan dalam menangani error yang terjadi pada saat runtime (program berjalan) atau yang lebih dikenal dengan sebutan runtime error. Secara umum, adanya kesalahan / error yang terjadi pada program pada saat runtime dapat menyebabkan program berhenti atau hang.
Apa saja tipe exception?NullPointerException. NullPointerException (NPE) adalah exception yang paling sering muncul. ... . 2. NumberFormatException. ... . 3. IllegalArgumentException. ... . 4. RuntimeException. ... . IllegalStateException. ... . 6. NoSuchMethodException. ... . 7. ClassCastException. ... . 8. Exception.. |