Skip to content

How to Write Your First Python Class with __init__ and Methods

Purpose

I wanted a clean, logical example of a Python class. I kept hearing about __init__ and self, but I could not connect them to real code.

Environment

  • Python 3.11
  • macOS

What happened?

I tried to read examples, but I skipped the smallest runnable version. That made the syntax feel like magic. So I wrote one class with one method and printed the output.

person.py
class Person:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def greet(self) -> str:
return f"Hi, I am {self.name} and I am {self.age} years old."
alice = Person("Alice", 22)
bob = Person("Bob", 35)
print(alice.greet())
print(bob.greet())
Terminal window
python3 person.py
Terminal window
Hi, I am Alice and I am 22 years old.
Hi, I am Bob and I am 35 years old.

That output made self feel less scary. It is just the current object.

How to solve it?

I used a two-step mental model. First, __init__ stores data on self. Second, methods read that data later.

If you are new to this, start from the tiniest example first. This one only has one attribute and one method.

minimal_pet.py
class Pet:
def __init__(self, name: str):
self.name = name
def speak(self) -> str:
return f"{self.name} says meow"
pet = Pet("Mimi")
print(pet.speak())
Terminal window
python3 minimal_pet.py
Terminal window
Mimi says meow

Once the minimal version works, you can extend it with more data and more methods.

wallet.py
class Wallet:
def __init__(self, owner: str, balance: int):
self.owner = owner
self.balance = balance
def deposit(self, amount: int) -> None:
self.balance += amount
def summary(self) -> str:
return f"{self.owner} has ${self.balance}"
w = Wallet("Sam", 50)
print(w.summary())
w.deposit(20)
print(w.summary())
Terminal window
python3 wallet.py
Terminal window
Sam has $50
Sam has $70

The reason

I think the key reason classes feel weird is that we see self everywhere and forget it is just the object. Once I treat it like a mailbox that stores state, the syntax stops being abstract.

Summary

In this post, I wrote my first Python class using __init__ and methods. The key point is storing data on self and calling methods on the object instance.

Final Words + More Resources

My intention with this article was to help others share my knowledge and experience. If you want to contact me, you can contact by email: Email me

Here are also the most important links from this article along with some further resources that will help you in this scope:

Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!

Comments