Python - Class Methods: A Beginner's Guide
Hello there, future Python enthusiasts! Today, we're going to embark on an exciting journey into the world of class methods in Python. Don't worry if you're new to programming – I'll be your friendly guide, explaining everything step by step. So, let's dive in!
What Are Class Methods?
Before we start, let's understand what class methods are. Imagine a class as a blueprint for creating objects. Class methods are special functions that belong to the entire class, not just to individual objects created from that class. They can access and modify class-level attributes, which are shared by all instances of the class.
Creating Class Methods in Python
There are two main ways to create class methods in Python. Let's explore both!
Using classmethod() Function
The first way to create a class method is by using the classmethod()
function. Here's how it looks:
class MyClass:
class_attribute = "I belong to the class"
def regular_method(self):
return "I'm a regular method"
@classmethod
def class_method(cls):
return f"I'm a class method and I can access {cls.class_attribute}"
# Creating an instance of MyClass
my_object = MyClass()
# Calling the class method
print(MyClass.class_method())
print(my_object.class_method())
In this example, class_method
is our class method. Notice how we use cls
instead of self
as the first parameter. This cls
represents the class itself, not an instance of the class.
Using @classmethod Decorator
The second way, which is more common and prettier (in my humble opinion), is using the @classmethod
decorator. It's like putting a special hat on our method to tell Python, "Hey, this is a class method!"
class Pizza:
restaurant = "Mama Mia's"
@classmethod
def change_restaurant(cls, new_restaurant):
cls.restaurant = new_restaurant
# Changing the restaurant name
Pizza.change_restaurant("Papa John's")
print(Pizza.restaurant) # Output: Papa John's
In this delicious example, we have a Pizza
class with a class method change_restaurant
. This method can change the restaurant
attribute for the entire class. Yum!
Access Class Attributes in Class Method
One of the super powers of class methods is their ability to access and modify class attributes. Let's see this in action:
class Student:
school = "Python High"
total_students = 0
def __init__(self, name):
self.name = name
Student.total_students += 1
@classmethod
def change_school(cls, new_school):
cls.school = new_school
@classmethod
def get_school_info(cls):
return f"Welcome to {cls.school}! We have {cls.total_students} students."
# Creating some students
alice = Student("Alice")
bob = Student("Bob")
print(Student.get_school_info())
# Output: Welcome to Python High! We have 2 students.
Student.change_school("Codecademy Academy")
print(Student.get_school_info())
# Output: Welcome to Codecademy Academy! We have 2 students.
Here, our class methods can access and modify the school
attribute and read the total_students
attribute. It's like they have VIP access to the class's secret information!
Dynamically Add Class Method to a Class
Did you know we can add methods to a class even after it's been defined? It's like giving our class new superpowers on the fly! Here's how:
class Car:
def __init__(self, brand):
self.brand = brand
def honk(cls):
return f"{cls.__name__} goes beep beep!"
# Adding the honk method to the Car class
Car.honk = classmethod(honk)
my_car = Car("Toyota")
print(my_car.honk()) # Output: Car goes beep beep!
We defined honk
outside the class and then added it as a class method. Now all our Car
objects can honk!
Dynamically Delete Class Methods
Just as we can add methods, we can also remove them. It's like giving our class a haircut – sometimes we need to trim away methods we no longer need:
class Smartphone:
@classmethod
def take_selfie(cls):
return "Cheese!"
@classmethod
def make_call(cls):
return "Dialing..."
# Let's remove the take_selfie method
del Smartphone.take_selfie
# This will work
print(Smartphone.make_call()) # Output: Dialing...
# This will raise an AttributeError
# print(Smartphone.take_selfie())
Be careful when deleting methods, though! Make sure you're not removing something you'll need later.
Wrapping Up
Congratulations! You've just taken your first steps into the world of Python class methods. Let's recap what we've learned:
Concept | Description |
---|---|
Class Method | A method that belongs to the class rather than instances |
classmethod() | A function to create class methods |
@classmethod | A decorator to create class methods |
cls parameter | Represents the class in class methods |
Accessing Class Attributes | Class methods can access and modify class attributes |
Dynamic Addition | We can add class methods after class definition |
Dynamic Deletion | We can remove class methods from a class |
Remember, practice makes perfect. Try creating your own classes and experiment with class methods. Before you know it, you'll be a Python class master!
Happy coding, and may your classes always be classy! ?✨
Credits: Image by storyset