How object and class attributes work in Python.

Caroline Del Carmen
2 min readMay 25, 2021

--

What’s being covered:

  • What’s a class attribute
  • What’s an instance attribute and the the differences between class and instance attributes
  • How to create and define a class

The first thing we want to do is discuss what object oriented programming (OOP) is. OOP is a style of programming that relies on things called classes and objects. It’s useful in giving programs structures that are useful, reusable pieces of code. Those structures are used to create individual instances of objects. Python is an object oriented programming language.

What is a class attribute?

A class is the blueprint for the structure. It is made up of attributes. If the class was a car, the attributes for the class would be for example, “color” and “brand”. A specific car, with a specific color and brand would be an instance of that class. For example one instance of the class “Car” could be a red Honda, while another instance could be a yellow Ford.

What is an instance attribute?

Continuing using the example above, while “color” and “brand” would be attributes of the class. “Red”, “yellow”, “Honda”, and “Ford” would be attributes of the specific instance. Meaning they are attributes that belong to a specific object, a specific instance of the car class.

There are three types of attributes: public, protected, and private.

Public: This attribute can be used and modified by everyone inside and outside of the class.

Protected: This attribute can be used outside of the class under specific conditions. The name is preceded by “__”.

Private: This attribute can only be used and modified inside the class. The name is preceded by “”__.

How to create and define a class:

Below is an example of how to create a class:

class Car:
'''This is an empty class''''
pass

Now this is an example of the same class with color and brand attributes:

class Car:
def __init___(self, color, brand):
self.color = color
self.brand = brand

The __init__ function initializes the class attributes whenever a new instance is created.

This is en example of the same class with private color and brand attributes.

class Car:
def __init___(self, color, brand):
self.__color = color
self.__brand = brand

For more information on classes I recommend this article on tutorialspoint.com: https://www.tutorialspoint.com/python/python_classes_objects.htm.

--

--

No responses yet