Data classes
As we learned from the Class instance initialization section, the canonical way to declare class instance attributes is through assigning them in the __init__()
method as in the following example:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
Let's assume we are building a program that does some geometric computation and Vector
is a class that allows us to hold information about two-dimensional vectors. We will display the data of the vectors on the screen and perform common mathematical operations, such as addition, subtraction, and equality comparison. We already know that we can use special methods and operator overloading to achieve that goal in a convenient way. We can implement our Vector
class as follows:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
"""Add two vectors using + operator"""
return...