Python Classes Full Guide
Beginner → Advanced
Prepared by ChatGPT
Table of Contents
1. Class Basics
2. __init__() Constructor
3. Instance vs Class Variables
4. Methods & self
5. Encapsulation (_protected, __private)
6. Inheritance
7. Overriding & Polymorphism
8. Class & Static Methods
9. Property Decorator (@property)
10. Special Methods (__str__, __repr__)
11. Dataclasses
12. Bank Account System Project (with input simulation)
1. Class Basics
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
p1 = Person('Alice', 25)
print([Link])
print([Link])
Alice
25
Explanation: Defines a simple class with attributes set by the constructor.
2. __init__() Constructor
class Car:
def __init__(self, model, year):
[Link] = model
[Link] = year
c = Car('Toyota', 2020)
print([Link], [Link])
Toyota 2020
Explanation: __init__ initializes instance attributes when object is created.
3. Instance vs Class Variables
class Counter:
total = 0 # class variable
def __init__(self):
[Link] += 1
c1 = Counter()
c2 = Counter()
print([Link])
2
Explanation: class variables shared across all instances; instance vars are per-object.
4. Methods & self
class Greeter:
def greet(self):
print('Hello from', self)
g = Greeter()
[Link]()
Hello from <Greeter object at ...>
Explanation: 'self' refers to the instance; methods operate on instance data.
5. Encapsulation (_protected, __private)
class BankAccount:
def __init__(self, owner, balance=0):
self._owner = owner # protected-ish
self.__balance = balance # name-mangled private
def get_balance(self):
return self.__balance
acc = BankAccount('Ali', 100)
print(acc.get_balance())
100
Explanation: Prefix '_' signals protected by convention; '__' invokes name mangling to reduce external
access.
6. Inheritance
class Animal:
def speak(self):
print('...')
class Dog(Animal):
def speak(self):
print('Woof')
Dog().speak()
Woof
Explanation: Subclass inherits methods and can override them.
7. Overriding & Polymorphism
class Shape:
def area(self):
raise NotImplementedError
class Square(Shape):
def __init__(self, s):
self.s = s
def area(self):
return self.s * self.s
shapes = [Square(3)]
for sh in shapes:
print([Link]())
9
Explanation: Different subclasses implement the same interface (area); code treats them uniformly.
8. Class & Static Methods
class MyClass:
@classmethod
def name(cls):
return cls.__name__
@staticmethod
def info():
return 'static info'
print([Link]())
print([Link]())
MyClass
static info
Explanation: @classmethod receives class as first arg; @staticmethod doesn't receive instance or
class.
9. Property Decorator (@property)
class Celsius:
def __init__(self, temp=0):
self._temp = temp
@property
def temp(self):
return self._temp
@[Link]
def temp(self, value):
if value < -273.15:
raise ValueError('Below absolute zero')
self._temp = value
c = Celsius(25)
print([Link])
[Link] = 30
print([Link])
25
30
Explanation: @property allows attribute-style access with getter/setter logic.
10. Special Methods (__str__, __repr__)
class Person:
def __init__(self, name):
[Link] = name
def __str__(self):
return f'Person({[Link]})'
p = Person('Maya')
print(p)
Person(Maya)
Explanation: __str__ controls human-readable string; __repr__ for developer representation.
11. Dataclasses (Python 3.7+)
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(2,3)
print(p)
Point(x=2, y=3)
Explanation: dataclasses reduce boilerplate for classes holding data.
12. Bank Account System (with input simulation)
This example simulates user input; the shown output is an example run.
class BankAccount:
def __init__(self, owner, balance=0):
[Link] = owner
[Link] = balance
def deposit(self, amount):
[Link] += amount
print(f"Deposited ${amount}. New balance: ${[Link]}")
def withdraw(self, amount):
if amount <= [Link]:
[Link] -= amount
print(f"Withdrew ${amount}. New balance: ${[Link]}")
else:
print("Insufficient funds.")
# Simulated input
owner = 'Alice'
account = BankAccount(owner)
[Link](500)
[Link](200)
print('Final balance:', [Link])
Deposited $500. New balance: $500
Withdrew $200. New balance: $300
Final balance: 300
Explanation: Simple account class with deposit/withdraw methods. Using variables simulates user input
for predictable output in the guide.