Initializing the Object
Learn what happens when we try to access the missing attribute and how to resolve it.
We'll cover the following...
Access missing attribute
If we don’t explicitly set the x
and y
positions on our Point
object, either using move()
or by accessing them directly, we’ll have a broken Point
object with no real position. What will happen when we try to access it?
Well, let’s just try it and see. Try it and see is an extremely useful tool for Python study. Open up the interactive interpreter and type away.
The following interactive session shows what happens if we try to access a missing attribute:
import mathclass Point:def move(self, x: float, y: float) -> None:self.x = xself.y = ydef reset(self) -> None:self.move(0, 0)def calculate_distance(self, other: "Point") -> float:return math.hypot(self.x - other.x, self.y - other.y)point = Point()point.x = 5print(point.x)print(point.y)
Well, at least it threw a useful exception. We probably seen them before (especially the ubiquitous SyntaxError, which means we typed something incorrectly!). At this point, simply be aware that it means something went wrong. ...