DEV Community

Cover image for Python Classes and Objects - Get to know how classes and objects work!
Michael Abraham Wekesa
Michael Abraham Wekesa

Posted on • Updated on

Python Classes and Objects - Get to know how classes and objects work!

Python is a high level and an object oriented programming language.
In python classes are used to construct objects, thus a class is a code template for creating objects.

A class being a blueprint for an object creation, it is a form of data structure that is user-defined, binding an objects data members and its methods in a single unit.

An object on the other hand is an instance of a class. Objects have states and behaviors. The state of an object represents its attributes and the behavior its methods.
An object must also have an identity in order of it to be identified uniquely.
Hence an object must have identity, state and behavior.

A real world example of a class and objects:

A car can be a class, as it is a template of a vehicle of any model, brand, different car engine size etc.
So lets define a car in a class template;

class: Car
State: model, color, brand
Behavior: fuel consumption

Using the class above, we can now create car objects:

First Object:

State

  • brand: Toyota
  • model: Corolla
  • color: Blue

Behavior

  • Fuel consumption: For every 35 kilometers it consumes 1 gallon of fuel.

Second Object :

State

  • brand: Honda
  • model: Civic
  • color: Green

Behavior

  • Fuel consumption: For every 40 kilometers it consumes 1 gallon of fuel.

From the first and second objects, they are both created from the same class but have different states and behaviors.

Creating a class in python
The keyword class is used in python to create a class, followed by the class name. It is best practice to have a class name with the UpperCaseCamelCase naming convention.

After defining the class name, the block of statements that follow for the specific class define its attributes and methods.
With python classes, there is Docstrings which is the first string in a class that briefly describes the class. It is not necessary but it is best practice in python classes, methods or functions to have docstrings.

We will use the example of the car class in the code examples:

Defining a class in Python

class Car:
    def __init__(self, color, brand, model):
       # instance variables(state)
       self.color = color
       self.brand = brand
       self.model = model

    # behavior (instance method)
    def car_details(self):
      print(f'Car brand: {self.brand}, model: {self.model}, color: {self.color}')

    # behavior (instance method)
    def fuel_consumption(distance=10, fuel_amount=1):
      print(f'For every {distance} kilometers it consumes {fuel_amount} gallon of fuel')

Enter fullscreen mode Exit fullscreen mode

The self keyword represents the instance of the class within itself. Meaning the class attributes and methods can be accessed within itself using the "self" keyword.

From the above class, with the fuel_consumption method, there are two parameters, this is to ensure that each object has its unique rate of fuel consumption based on a specific distance covered by the car object.

The __init__ is a type of function known as a constructor which in python is a special method used to create and initialize an object of a class.

Creating an object of a class
Here is how we get to create an object of an already defined class. We will use the Car class that we defined above;

toyota_corolla = Car(model='Corolla', brand='Toyota', color='Blue')

toyota_corolla.car_details()

Enter fullscreen mode Exit fullscreen mode

Output:

Car brand: Toyota, model: Corolla, color: Blue
Enter fullscreen mode Exit fullscreen mode

For the fuel_consumption method, we have to pass in the distance and fuel_amount arguments.

toyota_corolla = Car(model='Corolla', brand='Toyota', color='Blue')

toyota_corolla.fuel_consumption(distance=35, fuel_amount=1)

Enter fullscreen mode Exit fullscreen mode

Output:

For every 35 kilometers it consumes 1 gallon of fuel
Enter fullscreen mode Exit fullscreen mode

When defining the fuel_consumption method there is a default value for both fuel_amount and distance parameters, in case there are no arguments passed in, then the default values will be used instead. The default values are distance=10 and fuel_amount=1.

toyota_corolla = Car(model='Corolla', brand='Toyota', color='Blue')

toyota_corolla.fuel_consumption()

Enter fullscreen mode Exit fullscreen mode

Output:

For every 10 kilometers it consumes 1 gallon of fuel
Enter fullscreen mode Exit fullscreen mode

Class Attributes
When designing a class, there are two types of variables, the instance variables and the class variables.

Instance variables - These are attributes attached to an instance class. They are variables defined in the constructor, in the __init__ class method.

Class variables - Are attributes or variables declared in the class but outside any instance method including the __init__ method.

When accessing a class attribute can be accessed by using a dot on an instance followed by the attribute name; instance_name.attribute_name.

It is in the same way that an attribute can be modified, example(using the Car class):

toyota_corolla = Car(model='Corolla', brand='Toyota', color='Blue')

toyota_corolla.color = 'Yellow'
toyota_corolla.car_details()

Enter fullscreen mode Exit fullscreen mode

Output:

Car brand: Toyota, model: Corolla, color: Yellow
Enter fullscreen mode Exit fullscreen mode

From the above example, the Toyota Corolla's color is changed from Blue to Yellow.

Class Methods
With Object Oriented Programming a class can have 3 types of methods within the class:

Static Method: It is a general-purpose utility method that finishes just one task. We don't use instance or class variables within this static method because it doesn't have access to the class attributes.

Class Method: Used to access or modify the class's state. When implementing a method, if we only use class variables, we should declare that method as a class method.

Instance Method: Used to access or alter the status of the object. Methods are referred to as instance methods if they contain instance variables.

A class method is linked to the class itself, not to any class objects.
Only class variables are accessible to it.

Top comments (0)