Class and Instance Attributes in Python

Anthony Armour

Software Engineering Student at Holberton School

In this post, I am going to talk about classes, objects/instances, and attributes. I hope to explain their usage and functionality at a basic level. Programmers can create many brilliant structures to model real world problems with even simple implementation of classes and objects. Today I hope to introduce the basics of object oriented programming in Python and highlight the differences between class attributes and instance attributes. Let’s begin!

In object-oriented programming, classes are used to represent real world situations and data. Objects/instances are then created based on these classes. Each object’s behavior is defined by its class. Below is an example of a class and an object.

#class
class Dog():

def __init__(self, name, age):
self.name = name
self.age = age

#Object/Instance
my_dog = Dog("Sam", 4)

In this example, we have created a class Dog and an object/instance my_dog. It is common for class names to begin with an uppercase letter, while object/instances do not, for organizational reasons. Let’s take a look at what’s happening in the class Dog definition.

#class
class Dog():

def __init__(self, name, age):
self.name = name
self.age = age

Above, the class Dog is defined. Classes are made up of attributes and methods. In this example, “__init__” is a method, while “name” and “age” are instance attributes. Methods, which are similar to functions, are defined inside of a class, to be used by any object/instance of that class. Attributes are variables defined by a class, these variables hold many types of data, which is relevant to the functionality of the class. “self.name = name” takes the value stored in the parameter name and stores it in the variable name, which is then attached to the instance being created. The same process happens with “self.age = age”. Variables that are accessible through instances like this are called attributes. When an instance is created, the “__init__” method initializes the instance’s attributes which are defined in the class __init__ definition. These attributes are then local to that instance. This is different from Class attributes, which we will touch on later. Below shows how an object/instance can be created and it’s attributes initialized, and then have it’s attributes changed.

#Creates object/instance my_dog
#Initializes name and age
>>> my_dog = Dog("Sam", 4)
>>> print(my_dog.name)
Sam
>>> print(my_dog.age)
4
#Change instance attributes of my_dog>>> my_dog.name = "Tom"
>>> my_dog.age = 7
>>> print(my_dog.name)
Tom
>>> print(my_dog.age)
7

In this example, the attributes name and dog are initialized in the same line that the instance my_dog is created. The arguments passed to Dog(), “Sam and 4, correspond to the __init__() method which defines the attributes expected in the parameters. As shown again below, the objects/instances attributes can then be accessed using the dot “.” operator.

>>> print(my_dog.name)
Sam
>>> print(my_dog.age)
4

We can also use the dot “.” operator to reassign an instance attributes value. Below I will provide an example of instance attributes being local to their instance, which is relevant for the distinction between class attributes and instance attributes.

#Creates object/instance my_dog
#Initializes name and age
>>> my_dog = Dog("Sam", 4)
>>> new_dog = Dog("Katy", 2)
>>> print("{} and {}".format(my_dog.name, new_dog.name))
Sam and Katy
>>> print("ages are: {} and {}".format(my_dog.age, new_dog.age))
ages are: 4 and 2

Here we can see that every instance can have unique attribute values. Unlike instance attributes, class attributes have a constant value amongst all instances. I class attribute can be accessed by all instances. When a class attribute’s value is changed, the attribute value changes for all instances. Below is an example of how to define a class attribute, how to access it’s value through an instance, and how to change the class attribute’s value.

#class
class Dog():
#class attribute
favorite_food = "Bone"

def __init__(self, name, age):
self.name = name
self.age = age
#Creates object/instance my_dog
#Initializes name and age
>>> my_dog = Dog("Sam", 4)
>>> new_dog = Dog("Katy", 2)
>>> print(my_dog.favorite_food)
Bone
>>> print(new_dog.favorite_food)
Bone
#change class attribute
>>> Dog.favorite_food = "Beef"
>>> print(my_dog.favorite_food)
Beef
>>> print(new_dog.favorite_food)
Beef

In the example, we can see the main differences between class attributes and instance attributes. As shown, class attributes have a uniform value among all instances. These values can be changed using the dot “.” operator on the class name and giving it a value. When the value of a class attribute is redefined, the class attribute value is changed for all instances. This allows objects in a program to have unique instance attribute values, while also sharing specified class attributes that are common among all the objects sharing it’s class type. These attribute types can work in unison to create very dynamic data structures and programs. Below I will show how class attributes can be used to keep important data accessible to all objects/instances sharing the relevant class. The class attribute “number_of_dogs” will be used to keep a count of all the objects of class Dog that are initialized.

#class
class Dog():
#class attribute
number_of_dogs = 0

def __init__(self, name, age):
self.name = name
self.age = age
Dog.number_of_dogs += 1
#Creates object/instance my_dog
#Initializes name and age
>>> my_dog = Dog("Sam", 4)
>>> print(Dog.number_of_dogs)
1
>>> new_dog = Dog("Katy", 2)
>>> print(Dog.number_of_dogs)
2

Here, number_of_dogs is a class attribute that is used to count the number of objects of class type Dog are created. The number_of_dogs attribute is set to 0 in the class definition, and it’s incrementation happens inside the __init__() method. Each time a new object of class type dog is created, the __init__() method inside of class Dog executes to initialize the objects instance attributes. During it’s execution, it references the class attribute number_of_dogs using the dot “.” operator on the class name Dog and increments it by 1. This is shown above as the last line of the __init__() method. Lastly, I will give an example of how __dict__ retrieves the values and titles of instance attributes.

#Creates object/instance my_dog
#Initializes name and age
>>> my_dog = Dog("Sam", 4)
>>> new_dog = Dog("Katy", 2)
>>> print(my_dog.__dict__)
{'name': "Sam", 'age': 4}
>>> print(new_dog.__dict__)
{'name': "Katy", 'age': 2}

The combinations of class and instance attributes can create an incredibly wide range of data structures and programs. These simple building blocks can be nested and layered to create very complex systems. Utilizing class methods and attributes can be a very organized and efficient way to program. These tools can provide an easy method to keep and access information throughout a program. These are the most basic tool needed to practice object-oriented programming.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store