How to Define a Class in Python
A class bundles data and the code that works with it into one type of your own. You describe it once, then make as many objects from it as you need, each with its own data. This guide defines a Dog class with a name and a method, with real output from Python 3.15.2.
Syntax
class <ClassName>:
def __init__(self, <parameter>):
self.<attribute> = <parameter>
def <method>(self):
...
<object> = <ClassName>(<value>)
| Part | What it means |
|---|---|
class <ClassName>: | Starts the class. Class names usually start with a capital letter |
__init__ | Runs when an object is created, to set up its data |
self | The object itself. Every method takes it first, and Python passes it for you |
<ClassName>(<value>) | Creates an object. The values go to __init__ |
The Python tutorial: "Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made."
Prerequisites
- uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says woof"
rex = Dog("Rex")
print(rex.speak())

self.name = name: stores the name on the object, so its methods can use it.rex.speak(): calls the method; Python passesrexasself.
Step 2: Run It
uv run python dog.py
Rex says woof

The object kept its name, and its method used it.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
A method without self | TypeError: Dog.speak() takes 0 positional arguments but 1 was given: Python passed the object anyway | Make self the first parameter of every method |
Creating an object without the values __init__ needs | Dog() raised TypeError: Dog.__init__() missing 1 required positional argument: 'name' | Pass them: Dog("Rex") |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
takes 0 positional arguments but 1 was given on a method call | The method is missing self | Add self as its first parameter |
FAQ
Do two objects share their data?
No. Each object has its own attributes: with a second bella = Dog("Bella"), bella.speak() gave Bella says woof and rex.speak() still gave Rex says woof.
Why does the method get self when I don't pass it?
rex.speak() is the same as Dog.speak(rex), which also gave Rex says woof: Python fills in the object for you. That's why a method without self gets one argument more than it expects.
Conclusion
class Dog with __init__ and speak made a type of object, and Dog("Rex").speak() said Rex says woof. Every method takes self first.
Additional Resources
- Classes — the tutorial's chapter on classes.
- A first look at classes — class definitions, objects and methods.
