...

/

Adding Behaviors to Class Data With Properties

Adding Behaviors to Class Data With Properties

Learn and practice how we can add behaviors to our classes in Python.

Until now, we’ve focused on the separation of behavior and data. This is very important in object-oriented programming, but we’re about to see that, in Python, the distinction is uncannily blurry. Python is very good at blurring distinctions; it doesn’t exactly help us to think outside the box. Rather, it teaches us to stop thinking about the box.

Getter and setter methods

Before we get into the details, let’s discuss some bad object-oriented design principles. Many object-oriented developers teach us never to access attributes directly. They insist that we write attribute access like this:

Press + to interact
class Color:
def __init__(self, rgb_value: int, name: str) -> None:
self._rgb_value = rgb_value
self._name = name
def set_name(self, name: str) -> None:
self._name = name
def get_name(self) -> str:
return self._name
def set_rgb_value(self, rgb_value: int) -> None:
self._rgb_value = rgb_value
def get_rgb_value(self) -> int:
return self._rgb_value

The instance variables are prefixed with an underscore to suggest that they are private (other languages would actually force them to be private). Then, the get and set methods provide access to each variable. This class would be used in practice as follows:

Press + to interact
class Color:
def __init__(self, rgb_value: int, name: str) -> None:
self._rgb_value = rgb_value
self._name = name
def set_name(self, name: str) -> None:
self._name = name
def get_name(self) -> str:
return self._name
def set_rgb_value(self, rgb_value: int) -> None:
self._rgb_value = rgb_value
def get_rgb_value(self) -> int:
return self._rgb_value
c = Color(0xff0000, "bright red")
print(c.get_name())
c.set_name("red")
print(c.get_name())

The above example is not nearly as readable as the direct ...