How to handle Class and instance attributes in Python

Huy Nguyen
Python in Plain English
5 min readJan 13, 2021

--

Disclaimer: no dogs were harmed in the making

Python is a high level programming language designed for general purpose programming, it supports both Procedural and Object Oriented features. Python is multi-paradigm.

With procedural programming, a problem is broken down into functions. Each function does just one task. The main program is a series of calls to the different functions.

Object Oriented Programming (OOP) allows the programmer to couple data structure and related functionality (behavior, methods for accessing and manipulating the data) into objects. This entails describing the objects in terms of their class.

The class & instance attributes are specific to OOP.

OOP is an approach for modeling real-world things, like, for instance pets, as well as relations between pets, like families and friends, owners, and so on.

Class & Instance

A Class is a blueprint that defines an object. It is analogous to a form / template with blank fields or attributes.

A Dog class specifies attributes or characteristics that are required for defining a dog, but it doesn’t contain any data specific to any dog. These attributes could be breed, name, age and owner. To keep it simple I’ll just use name and age.

An Instance is an object that is built from a class and contains real data, like a form that has been filled out with information. For example, an instance of the Dog class contains a name, like Sam, who’s four year-old.

Instance attributes

The Pythonic way to create instance attributes is with a method called .__init__(). It’s usually the first method defined inside a class. Every time a new object is created, .__init__() sets the initial state of the object by assigning the values of the object’s attributes.

Class methods have an extra first name that has to be added to the beginning of the parameter list. Python will give a value for this parameter. This particular variable refers to the object itself, and by convention, it is given the name self.

Class Dog — Instance attributes

Attributes created in .__init__() are called instance attributes.

All Dogobjects have a name and an age, but the values for the name and age attributes will vary depending on the Dog instance.

For example: the dog sam is called “Sam” and is 4 year-old.

Now if you would like to add some verification of the input value you could have put this in the .__init__().

Class Dog — input validation

The Pythonic way to validate instance attributes is with the Getter and Setter properties. When a new object is created, the.__init__() method calls the setter property to set the value of the attribute. You will be able to parse and sanitize the input data before assigning it to the instance attributes. Errors can be raised if the requirements are not met. It’s also possible to define how (public, private, protected) getting the attribute value will be available from outside. Also, adding type and value validation in the setter will centralize the logic in one place.

Class Dog — Validate type & value of an instance attribute

Class attributes

Class Dog — class attribute

Class attributes have the same value for all class instances. The Pythonic way to define a class attribute is to assign a value to a variable name outside of .__init__().

When an instance of the class is created, class attributes are automatically created and assigned to their initial values.

For example: all Dog objects share the same class attribute species.

Differences between class and instance attributes

Class attributes define properties that have the same value for every class instance. Instance attributes vary from one instance to another.

Class attribute can be accessed via an instance or the class name, whereas an instance attribute can only be accessed via the instance to which it belongs.

Advantages and drawbacks of class and instance attributes

One of the biggest advantages of using classes to organize data is that instances are guaranteed to have the attributes you expect. All Dog instances have species, name and age attributes, so you can use those attributes with confidence knowing that they will always return a value.

These attributes can be used whenever needed, meaning less code must be rewritten and not all of it has to be imported.

Sometimes it can prove hard to keep track of every class and method you created so everything must be kept neatly organized and with proper notes.

Namespaces helps to deal with attributes

In Python, a namespace is a mapping between objects and names. To keep it simple, let’s say it is a Python dictionary that has as a key to the name of the object and its value as a value.

Classes and instances have different namespaces, for our example, we have Dog.__dict__ as a namespace for our class Dog and sam.__dict__as a namespace for our instance sam.

When you access an attribute (instance or class attribute) as a property of an object using the dot convention, it searches first in the namespace of that instance for that attribute name. If it is found, it returns the value, otherwise, it searches in the namespace of the class. If nothing is found there as well, it will raise an AttributeError. The instance namespace is look up before the class namespace.

Class Dog — dictionaries

Both the class and the instance have a dictionary with attribute keys and values. The class dictionary stores multiple built-in attributes that an instance does not contain.

Thank you for reading !

Bye for now

--

--