Skip to main content

Python Classes & Usages

· 3 min read
Nziie

What are Python classes?

To put it simply, Python classes are like an object constructor or a "blueprint" for creating objects. You can also create a class to organize commands or event listeners and load them later using Pycord or discord.js.

Breakdown

Lets break down a simple class of a Car.

So here is our code that we're working with...

car.py
class Car:
def __init__(self, year, made, model): # When you use 'Car()' you will pass
# in these values that are set in the class
self.year = year
self.made = made
self.model = model

def start(self):
print('Vrrroooooooooommmm!!!')

def turn_off(self):
print('*Powering down...*')

def year_made(self):
return self.year

def month_made(self):
return self.made

def show_model(self):
return self.model

my_car = Car(2000, 'December', 'Lexus') # Create the car from the class
# Setting the year to 2000, the month to 'December' and
# and the model to 'Lexus'
my_car.start() # >>> 'Vrrroooooooooommmm!!!'
my_car.year_made() # >>> 2022
my_car.show_model() # >>> 'Lexus'
my_car.month_made() # >>> 'December'
my_car.turn_off() # >>> '*Powering down...*'

The class Car has some functions being start, turn_off, year_made, month_made, and show_model. All of these functions return or print a value from the class, the values being the attributes of the class (year, made, and model). You can access these attributes by doing car.year, etc.

If you're using Pycord or discord.py it would look something like this...

mycog.py
import discord
from discord.ext import commands

class MyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot # you can access your bot object here

### stuff ###

def setup(bot):
bot.add_cog(MyCog(bot))

Then in your main.py or bot.py file...

main.py
# ...

# if you have your cog file in a 'cogs' folder:
bot.load_extension('cogs.mycog')
# if you don't:
bot.load_extension('mycog')

Functions Setting Attributes

You can even make functions to set attributes within the class.

car.py
class Car:
def __init__(self, year, made, model):
self.year = year
self.made = made
self.model = model

def start(self):
print('Vrrroooooooooommmm!!!')

def turn_off(self):
print('*Powering down...*')

def year_made(self):
return self.year

def month_made(self):
return self.made

def show_model(self):
return self.model

def set_year(self, year):
self.year = year
print(f'Set year to: {year}')

my_car = Car(2000, 'December', 'Lexus')
my_car.year_made() # >>> 2000
my_car.set_year(2005) # >>> 'Set year to: 2005'
my_car.year_made() # >>> 2005

Make sure you have correct syntax in or you will get an error!