Gianni Castellano
Posted on July 11, 2024
In Python, classes are the foundation of object-oriented programming. In simple terms, they are essentially a template for creating objects with similar attributes.
Creating Classes
Class definition syntax is extremely straightforward. All you need is the keyword: class followed by the ClassName: (the class name is always in UpperCamelCase). I have provided an example below:
class Shop:
Well done you have successfully created a class! Now we will take a deeper dive into how you can use them. I will be using a class to create and store different shops throughout this blog.
Using Classes
The first step after creating your class is to use a constructer method know as the init method to initialize instance attributes that will be used when instantiating objects.
class Shop:
def __init__(self, name, location, owner):
self.name = name
self.location = location
self.owner = owner
Now whenever we create or instantiate a new store/shop object within this class it will share these attributes we initialized! Now lets create some shops:
class Shop:
def __init__(self, name, location, owner):
self.name = name
self.location = location
self.owner = owner
#method for displaying our stores
def display_store_info(self)
return f"Shop: {self.name}, Location: {self.location}, Owner: {self.owner}"
#creating shop instances
first_shop = Shop("FoodMart", "Main Street", "John Smith")
second_shop = Shop("ClothingStore", "Billybob Avenue", "Billy Bob")
Now in our python shell if we type print(first_shop.display_store_info()) we will see this display:
Shop: FoodMart, Location: Main Street, Owner: John Smith
We could also do the same for the second_shop! We created a method or function in our class called display_store_info that allowed us to inject the attributes defined in our init. Now we could make limitless shop objects that include the name, location, and owner as a reusable template.
This is just the beginning when it comes to classes. The possibilities and reusability is incredible when it comes to using classes in Python. I would love to go into more detail in a future blog post but this is just a small little intro.
Posted on July 11, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.