Python Classes and Objects (43/100 Days of Python)

Martin Mirakyan
5 min readFeb 13, 2023

--

Day 43 of the “100 Days of Python” blog post series covering classes and objects in Python

Python is a powerful and flexible programming language that is widely used for a variety of applications. One of the most important concepts in Python is object-oriented programming (OOP), which is used to model real-world scenarios in code. In this tutorial, we will explore the basics of classes and objects in Python, including what they are, how they work, and how to use them to create real-world examples.

What is a Class in Python?

A class in Python is a blueprint for creating objects. It defines the attributes and methods that the objects created from it will have. A class serves as a template for creating multiple objects that share the same attributes and methods. Classes are created using the class keyword in Python:

class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed

def bark(self):
print(f'{self.name} barks!')

The above class, Dog, has two attributes: name and breed, and a method called bark. The __init__ method is a special method in Python classes that is called when an object is created from the class. The self keyword is a reference to the instance of the object that is being created. In other words, self refers to the specific object that is being created from the class.

What is an Object in Python?

An object is an instance of a class. When we create an object from a class, we are creating a specific instance of that class with its own unique values for the attributes defined in the class. Here’s how we create an object from the Dog class:

dog = Dog('Loby', 'Labrador')

The dog object now has its own values for the name and breed attributes and can call the bark method:

print(dog.name)    # 'Loby'
print(dog.breed) # 'Labrador'
dog.bark() # 'Loby barks!'

The self Keyword

The self keyword is a special parameter that is passed to every method in a class in Python. It refers to the instance of the class, and is used to access the attributes and methods of that instance. So, the self keyword “keeps track” of the current object.

In the Dog class defined earlier, the self parameter is used to access the name attribute. Without self, the code would not know which instance of the class it is referring to, and the attributes and methods of the class would not be accessible.

The self parameter is automatically passed to the method when it is called on an instance of the class. For example, when we call dog.bark(), Python automatically passes dog as the value of self to the bark method. This allows the method to access and manipulate the attributes of the instance:

dog1 = Dog('Loby', 'Labrador')
dog2 = Dog('Riko', 'Akita Inu')

dog1.bark() # Loby barks!
dog2.bark() # Riko barks!

Notice that the methods in the class are just functions. The only difference is that they accept a parameter called self and can access the values of the object using the self argument. This makes using classes especially useful as everything can be grouped together in a simple, concise, and organized way.

Naming Conventions for Classes in Python

Class and method naming in Python follow certain conventions to make the code readable and understandable to other developers. In Python, it is recommended to use the CamelCase naming convention for class names, which means that each word in the class name starts with a capital letter, with no underscores. For example, a class named Book or Textbook is written in the correct naming convention, while book or Text_book isn’t.

For method names, it is recommended to use snake_case, which means that all words in the method name are separated by underscores, and all letters are in lowercase. The method names should also be descriptive and indicate what the method does. For example, check_out and check_in are well-named methods for the Book class, while checkOut or CheckOut are not.

Another convention in Python is to use the double underscores (__) prefix for special methods such as __init__. These special methods have specific purposes and are used in the implementation of Python's OOP features. For example, the __init__ method is used to initialize the attributes of an object when it is created, and the __str__ method is used to define the string representation of an object.

By following these naming conventions and principles, we can create clean and readable code that is easy to understand and maintain.

Real World Example

Now let’s use classes and objects to model a real-world scenario. Let’s say we want to model a library system. We could create a Book class to represent a book in the library, and a Library class to represent the library itself.

class Book:
def __init__(self, title, author, ISBN):
self.title = title
self.author = author
self.ISBN = ISBN
self.checked_out = False

def check_out(self):
if self.checked_out:
print(f'{self.title} is already checked out.')
else:
self.checked_out = True
print(f'{self.title} has been checked out.')

def check_in(self):
if not self.checked_out:
print(f'{self.title} is not checked out.')
else:
self.checked_out = False
print(f'{self.title} has been checked in.')


class Library:
def __init__(self, name):
self.name = name
self.books = []

def add_book(self, book):
self.books.append(book)
print(f'{book.title} has been added to the library.')

def check_out_book(self, ISBN):
for book in self.books:
if book.ISBN == ISBN:
book.check_out()
break
else: # no-break (the program didn't enter the if to break out of the loop)
print(f'Book with ISBN {ISBN} not found.')

def check_in_book(self, ISBN):
for book in self.books:
if book.ISBN == ISBN:
book.check_in()
break
else:
print(f'Book with ISBN {ISBN} not found.')

We can now create a Library object and add Book objects to it:

alexandria = Library('The Library of Alexandria')

# As everything was destroyed in the library, we add our own collection :)
book1 = Book('Pride and Prejudice', 'Jane Austen', '1234567890')
book2 = Book('To Kill a Mockingbird', 'Harper Lee', '2345678901')

alexandria.add_book(book1) # Add the first book to the library
alexandria.add_book(book2) # Add the second book to the library
print(alexandria.name) # The Library of Alexandria

In this example, we create two Book objects, book1 and book2, with different attributes. After which, we add those books to the library object called my_library. We can also check out and check in books:

alexandria.check_out_book('1234567890') # Pride and Prejudice has been checked out.
alexandria.check_out_book('1234567890') # Pride and Prejudice is already checked out.
alexandria.check_in_book('1234567890') # Pride and Prejudice has been checked in.

What’s next?

--

--

Martin Mirakyan
Martin Mirakyan

Written by Martin Mirakyan

Software Engineer | Machine Learning | Founder of Profound Academy (https://profound.academy)

No responses yet