Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Object-Oriented Python

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Python

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.

One class Car is a blueprint; calling Car() twice builds two separate objects, my_car and your_car, at different places in memory class Car the blueprint Car() Car() object No. 1 my_car object No. 2 your_car is → False
One class, two objects. Same blueprint, different places in memory.

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:

  1. Python first makes a new, empty object.
  2. Then it runs __init__ on its own, and self is that new empty object.
  3. self.name = name puts "Alice" on the object, and self.grade = grade puts "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.

Attribute lookup: rex.name is found on the object; rex.species is not on the object, so Python goes up to the Dog class, where bella.species also lands class Dog species = "Canis familiaris" rex name="Rex", breed="Labrador" bella name="Bella", breed="Poodle" .species: not here, go up .species: same place
Python looks on the object first, then on the class.

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 nameStyleExample
Constantall capitals with underscoresMAX_SPEED
ClassPascalCase, each word starts with a capitalElectricCar
Variable, attribute, methodsnake_case, all small with underscoresmy_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.
  • self is 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 self fails 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 19 of 48

Previous
Python Class Methods, Static Methods and Properties: What Each One Receives
Next post
Python Inheritance and Polymorphism: super(), Overriding and Duck Typing

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.

On this page

  • Your first class
  • What __init__ really does
  • What self really is
  • Class attributes and instance attributes
  • Instance methods use the object's data
  • Putting it together: a small bank account
  • The most common mistake: a missing self
  • Naming, the PEP 8 way
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.