class

In Python, a class is a blueprint for creating objects, providing initial values for state (attributes) and implementations of behavior (methods or functions). Classes encapsulate data for the object and provide methods for interacting with that data.

You define a class using the class keyword followed by the class name and a colon. Inside the class, you define methods, including the special method .__init__(), which initializes new objects.

Classes enable you to implement the principles of object-oriented programming (OOP) like encapsulation, inheritance, and polymorphism, helping you write more organized and reusable code.

Example

Here’s a quick example of defining and using a class in Python:

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

    def speak(self):
        return f"{self.name} says woof!"

# Usage
frieda = Dog("Frieda", 5)

# Call the .speak() method
print(frieda.speak())  # Output: Frieda says woof!

# Access attributes
print(f"Name: {frieda.name}")  # Output: Name: Frieda
print(f"Age: {frieda.age}")    # Output: Age: 5

# Modify attributes
frieda.age += 1
print(
    f"{frieda.name} is now {frieda.age} years old."
)  # Output: Frieda is now 6 years old.

In this example, Dog is a class with an initializer method .__init__() that sets up the .name and .age attributes. The .speak() method returns a string representing the dog’s bark. You create an instance of Dog by calling Dog() with appropriate values for each argument to .__init__().

Tutorial

Python Classes: The Power of Object-Oriented Programming

In this tutorial, you'll learn how to create and use full-featured classes in your Python code. Classes provide a great way to solve complex programming problems by approaching them through models that represent real-world objects.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 21, 2025 • Reviewed by Dan Bader