October 2018
Beginner to intermediate
466 pages
12h 2m
English
Now, we have a basic class, but it's fairly useless. It doesn't contain any data, and it doesn't do anything. What do we have to do to assign an attribute to a given object?
In fact, we don't have to do anything special in the class definition. We can set arbitrary attributes on an instantiated object using dot notation:
class Point:
pass
p1 = Point()
p2 = Point()
p1.x = 5
p1.y = 4
p2.x = 3
p2.y = 6
print(p1.x, p1.y)
print(p2.x, p2.y)
If we run this code, the two print statements at the end tell us the new attribute values on the two objects:
5 4 3 6
This code creates an empty Point class with no data or behaviors. Then, it creates two instances of that class and assigns each of those instances x and y coordinates to identify ...
Read now
Unlock full access