The world’s leading publication for data science, AI, and ML professionals.

Managing Instance Attributes in Python

Creating Managed Attributes in Python

Source
Source

Often times in the implementation of a Python class, it would be useful if we could easily add extra processing to getting and/or setting an instance attribute. For example, it would be useful to be able to perform type checking or some other form of validating during getting/setting instance attributes. In this post, we will discuss how to manage instance attributes in python.

Let’s get started!

Suppose we have a class called ‘Cars’ with an attribute called ‘car_brand’:

class Car:
    def __init__(self, car_brand):
       self.car_brand = car_brand

Let’s initialize a car class instance as a ‘Tesla’:

car1 = Car('Tesla')
print("Car brand:", car1.car_brand)

While this works fine, if we initialize an instance with a bad input value for ‘car_brand’, there is no data validation or type checking. For example, if we initialize a car instance with a car brand value of the number 500:

car2 = Car(500)
print("Car brand:", car2.car_brand)

we should have a way of validating the type of this instance attribute. We can customize access to attributes by defining the ‘car_brand’ attribute as a ‘property’:

class Car:
    ...
    @property
    def car_brand(self):
        return self._car_brand

Defining ‘car_brand’ as a ‘property’ allows us to attach setter and deleter functions to our ‘car_brand’ property. Let’s add a setter method to our ‘car_brand’ attribute that raises an error if the instance is initialized with a value that is not a string:

class Car:
    ...
    #setter function
    @car_brand.setter
    def car_brand(self, value):
        if not isinstance(value, str):
            raise TypeError('Expected a string')
        self._car_brand = value

Let’s define our instance again, with our integer input 500:

car2 = Car(500)
print("Car brand:", car2.car_brand)

Another instance management operation to consider is the deletion of instance attributes. If we look at our initial instance:

car1 = Car('Tesla')
print("Car brand:", car1.car_brand)

We can easily delete the attribute value:

car1 = Car('Tesla')
print("Car brand:", car1.car_brand)
del car1.car_brand
print("Car brand:", car1.car_brand)

We can add a deleter function that raises an error upon attempted deletion:

class Car:
    ...
    #deleter function
    @car_brand.deleter
    def car_brand(self):
        raise AttributeError("Can't delete attribute")

Let’s try to set and delete the attribute value once again:

car1 = Car('Tesla')
print("Car brand:", car1.car_brand)
del car1.car_brand

I’ll stop here but feel free to play around with the code yourself.

CONCLUSIONS

To summarize, in this post we discussed how to manage instance attributes in python classes. We showed that by defining a class attribute as a ‘property’ we can attach setter and deleter functions that help us manage the access of attributes. I hope you found this post useful/interesting. The code from this post is available on GitHub. Thank you for reading!


Related Articles