Python Classes and Objects: __init__, self and PEP 8 Names
A class is the blueprint and an object is what you build from it. Car, Student, Dog, Circle and BankAccount show what __init__ and self really do, how attribute lookup works, the missing self error, and PEP 8 names.
What you will learn
- Explain the difference between a class and an object, and check it with type() and is
- Describe what __init__ does when you build an object, and what self is
- Tell class attributes from instance attributes and how Python looks them up
- Name constants, classes and methods the PEP 8 way
Before you start
- Python functions and return values
- Running a .py file in PyCharm or a terminal
So far you've kept data in variables and logic in functions, in separate places. A class keeps them together. That's the whole idea of object oriented programming, and everything in this article builds on it.
Think about a blueprint for a house. It's only a drawing, and nobody can live in it. But from one blueprint you can build as many houses as you like, each at its own address. Paint one house blue and the other one doesn't change, because they're two separate houses. A class is the blueprint. An object is the house.
Your first class
The class keyword creates a blueprint. This one is empty, so we write pass, and that's fine.
class Car:
pass
my_car = Car()
your_car = Car()
print(type(my_car))
print(my_car is your_car)
<class '__main__.Car'>
False
Car() with brackets builds one object, and my_car points to it. Call it again and you get a second object somewhere else in memory. type() says it's a Car, so a class is really a type you made yourself. And my_car is your_car is False: same blueprint, two different objects.
What __init__ really does
An empty object isn't much use. Let's give a student a name and a grade.
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
alice = Student("Alice", "A")
bob = Student("Bob", "B+")
print(alice.name, alice.grade)
print(bob.name, bob.grade)
Alice A
Bob B+
Look at Student("Alice", "A") step by step:
- Python first makes a new, empty object.
- Then it runs
__init__on its own, andselfis that new empty object. self.name = nameputs "Alice" on the object, andself.grade = gradeputs "A" next to it.
Bob goes through the same steps on his own separate object, so each one prints its own values. So __init__ doesn't create the object. It fills in an object that already exists. The values it sets are called instance attributes.
What self really is
Here's a method called greet:
class Student:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hi, I'm {self.name}"
s1 = Student("Alice")
print(s1.greet())
print(Student.greet(s1))
Hi, I'm Alice
Hi, I'm Alice
When you write s1.greet(), Python takes the object before the dot and passes it in as the first argument. That's self. Inside the method, self.name means this object's name, which is Alice.
The second line proves it. Student.greet(s1) is the long way of writing the same call, and the output is identical. So self is just the object the method was called on. You could use another name, but always keep self; everyone reading your code expects it.
Class attributes and instance attributes
class Dog:
species = "Canis familiaris"
def __init__(self, name, breed):
self.name = name
self.breed = breed
rex = Dog("Rex", "Labrador")
bella = Dog("Bella", "Poodle")
print(rex.name, "|", bella.name)
print(rex.species)
print(bella.species)
Rex | Bella
Canis familiaris
Canis familiaris
species sits outside __init__, directly in the class, so there's one copy and it lives on the class. name and breed are set inside __init__, so Rex and Bella each get their own.
When you ask for rex.name, Python looks on the object, finds it, and stops. rex.species isn't on the object, so Python goes up to the class and finds it there. Bella goes up to the very same place, which is why both lines print the same text. Values that belong to each object go in __init__. Values shared by all of them go on the class.
Instance methods use the object's data
A method is a function that lives in a class and works on the object's data.
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
def describe(self):
return f"r={self.radius}, area={self.area():.2f}"
c = Circle(5)
print(c.area())
print(c.describe())
78.53975
r=5, area=78.54
In c.area(), self is c, so self.radius is 5 and the formula gives 78.53975. describe calls self.area() from inside, so one method can use another, and :.2f rounds it to 78.54. Notice we never passed the radius in again. The object remembers it. That's what you get from keeping data and logic together.
Putting it together: a small bank account
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds")
return
self.balance -= amount
alice = BankAccount("Alice", 1000)
bob = BankAccount("Bob", 500)
alice.deposit(250)
alice.withdraw(100)
bob.withdraw(800)
print("Alice:", alice.balance)
print("Bob:", bob.balance)
Insufficient funds
Alice: 1150
Bob: 500
Alice starts at 1000, deposits 250 (1250) and withdraws 100 (1150). Bob tries to take 800 out of 500. The check sees that's more than his balance, prints "Insufficient funds" and returns, so his balance never changes. Same class, same methods, and each object looks after its own balance.
The most common mistake: a missing self
class Broken:
def greet():
return "Hello"
b = Broken()
print(b.greet())
Traceback (most recent call last):
File "S03L01_Classes\missing_self.py", line 7, in <module>
print(b.greet())
~~~~~~~^^
TypeError: Broken.greet() takes 0 positional arguments but 1 was given
Read the last line. greet takes 0 positional arguments, but 1 was given. That one argument is the object Python passed in, even though you didn't write it. There's no parameter to receive it, so the call fails. Add self and it works:
class Fixed:
def greet(self):
return "Hello"
f = Fixed()
print(f.greet())
Hello
Whenever you see "takes 0 positional arguments but 1 was given" on a method, check for self first.
Naming, the PEP 8 way
Python has a style guide called PEP 8. One small file shows all three naming styles you'll use every day:
MAX_SPEED = 120
class ElectricCar:
def __init__(self, top_speed):
self.top_speed = top_speed
def is_legal(self):
return self.top_speed <= MAX_SPEED
my_car = ElectricCar(100)
print(my_car.is_legal())
True
| Kind of name | Style | Example |
|---|---|---|
| Constant | all capitals with underscores | MAX_SPEED |
| Class | PascalCase, each word starts with a capital | ElectricCar |
| Variable, attribute, method | snake_case, all small with underscores | my_car, top_speed, is_legal |
You don't have to memorise these. When you prompt an AI tool, add one line: "follow PEP 8 naming". Then when you read the code it gives you, the name alone tells you what kind of thing it is.
Quick recap
- A class is the blueprint, an object is what you build from it, and
__init__fills that object in. selfis the object the method was called on. Python passes it for you.- Python looks for an attribute on the object first, then on the class.
- A method with no
selffails with "takes 0 positional arguments but 1 was given".
Next, the three kinds of method a class can hold are covered in class methods, static methods and properties.
Try it yourself
Add a transfer method to BankAccount that moves money from one account to another and refuses if there isn't enough. Or prompt an AI tool to write it, then read every line it gives you.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Class Methods, Static Methods and Properties: What Each One Receives
Instance methods get self, class methods get cls, static methods get nothing. Then properties, setters and deleters, with small runnable files and their real output.
Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
A child class gets everything from its parent, Python walks up and stops at the first match, and super() reaches the parent. Then polymorphism: one call, a different method for each object, with Animal, Employee and Shape examples and their real output.
Python Multiple Inheritance, the MRO and Mixins
A class can have two parents or a whole chain of them, and one list puts them in order: the MRO. Read it, watch Python walk it, see super() follow it, and build JsonMixin and LogMixin for a User class.
Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
Python has no private keyword: one underscore is a sign, two underscores is a rename, and nothing is locked. Then the dunder methods that let print, ==, +, len, [] and for work on your own Book, Song, Vector and Playlist objects.
