Skip to main content

How to Define a Class in Python

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
class <ClassName>:
def __init__(self, <parameter>):
self.<attribute> = <parameter>

def <method>(self):
...

<object> = <ClassName>(<value>)
PartWhat 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
selfThe 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​

dog.py
class Dog:
def __init__(self, name):
self.name = name

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


rex = Dog("Rex")
print(rex.speak())

The dog.py script in a macOS-style code window: class Dog with init storing self.name and a speak method returning the name and says woof, then rex = Dog("Rex") and print(rex.speak()).

  • self.name = name: stores the name on the object, so its methods can use it.
  • rex.speak(): calls the method; Python passes rex as self.

Step 2: Run It​

Terminal
uv run python dog.py
Output
Rex says woof

The script's output in a terminal: Rex says woof.

The object kept its name, and its method used it.

Common Mistakes​

MistakeWhat happensDo this instead
A method without selfTypeError: Dog.speak() takes 0 positional arguments but 1 was given: Python passed the object anywayMake self the first parameter of every method
Creating an object without the values __init__ needsDog() raised TypeError: Dog.__init__() missing 1 required positional argument: 'name'Pass them: Dog("Rex")

Troubleshooting​

SymptomLikely causeFix
takes 0 positional arguments but 1 was given on a method callThe method is missing selfAdd 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​