Python Class and Instance Attributes

Mike Mbea
3 min readJan 13, 2021

In Python and other Object-Oriented languages, classes are considered the blueprint to creating objects. An instance is a copy of the class with actual values.

To define a class in Python3, you can do the following:

Class Attributes

Class attributes are attributes which are owned by the class itself. They will be shared by all the instances of the class. Therefore they will have the same value for every instance. We define class attributes outside of all the methods, usually, they are placed at the top, right below the class header.

Instance Attributes

Instance attributes are owned by the specific instances of a class. This means for two different instances the instance attributes are usually different. Let’s give our Dog class an instance attribute, “name”.

The Pythonic way

Python has a particular way to do getters and setters. The conventional method involves placing dunders for private methods/attributes and underscores for protected methods/attributes. The property and setter decorators are also used to signify methods as setters/getters.

Differences between class and instance attributes

The biggest differences between class and instance attributes are that class attributes can be declared outside of methods and exist across different instances of classes. Instance attributes, however, use setter methods to instantiate clones of the parent class.

Advantages and drawbacks

The advantage of having instance attributes is that you can parse and sanitize the data the user passes in before assigning it to the instance of the class. This also means you can throw errors if it doesn’t fit the requirements you set. The objects that are created also can be unique within the confines of the setter methods. Drawbacks include

__dict__

If you want to check all of your class attributes, you can use the special method __dict__ to list them.

I think that now,you know more a Class and Instance attributes in Python.If you like what you’ve read,feel free to follow me on Twitter.

--

--