0% found this document useful (0 votes)
7 views17 pages

Python Classes Tutorial Guide

Uploaded by

Amit Agarwal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views17 pages

Python Classes Tutorial Guide

Uploaded by

Amit Agarwal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

very detailed tutorial on class python

Comprehensive Python Classes Tutorial

Table of Contents
1. Introduction to Classes

2. Class Syntax and Structure

3. Class Attributes vs Instance Attributes

4. Methods

5. Special Methods (Magic/Dunder Methods)

6. Inheritance

7. Polymorphism

8. Encapsulation

9. Property Decorators

10. Class Methods and Static Methods

11. Advanced Topics

12. Best Practices

1. Introduction to Classes <a name="introduction"></a>

What are Classes?

Classes are blueprints for creating objects. They encapsulate data (attributes) and
functionality (methods) together.

Why Use Classes?

Organization: Group related data and functions

Reusability: Create multiple instances with same structure

Modularity: Isolate functionality into self-contained units

Inheritance: Share common functionality between related classes

[Link] 1/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

2. Class Syntax and Structure <a name="syntax"></a>

Basic Class Definition

python

class ClassName:
"""Optional class documentation string"""
class_attribute = "I'm a class attribute"

def __init__(self, parameter1, parameter2):


"""Constructor method - called when creating instances"""
self.instance_attribute1 = parameter1 # Instance attribute
self.instance_attribute2 = parameter2

def instance_method(self):
"""Instance method - operates on instance data"""
return f"Values: {self.instance_attribute1}, {self.instance_attribute2}"

Creating Instances

python

# Creating objects (instances) of the class


obj1 = ClassName("hello", 42)
obj2 = ClassName("world", 100)

print(obj1.instance_method()) # Values: hello, 42


print(obj2.instance_method()) # Values: world, 100

3. Class Attributes vs Instance Attributes <a


name="attributes"></a>

Instance Attributes

Specific to each object instance

Defined in __init__ using self.attribute_name

Each instance has its own copy

Class Attributes
[Link] 2/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

Shared among all instances

Defined directly in the class body

Changed for all instances when modified

python

class Car:
# Class attribute - shared by all instances
wheels = 4
count = 0 # Track how many cars created

def __init__(self, brand, model, year):


# Instance attributes - unique to each instance
[Link] = brand
[Link] = model
[Link] = year
[Link] += 1 # Modify class attribute

def display_info(self):
return f"{[Link]} {[Link]} {[Link]} with {[Link]} wheels"

# Usage
car1 = Car("Toyota", "Camry", 2022)
car2 = Car("Honda", "Civic", 2023)

print(car1.display_info()) # 2022 Toyota Camry with 4 wheels


print(car2.display_info()) # 2023 Honda Civic with 4 wheels

# Modify class attribute


[Link] = 6
print(car1.display_info()) # Now shows 6 wheels for both

print(f"Total cars created: {[Link]}") # Total cars created: 2

4. Methods <a name="methods"></a>

Instance Methods

Most common type of method

First parameter is always self (reference to instance)

Can access and modify instance attributes

[Link] 3/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

python

class BankAccount:
def __init__(self, account_holder, balance=0):
self.account_holder = account_holder
[Link] = balance
[Link] = []

def deposit(self, amount):


"""Instance method to deposit money"""
if amount > 0:
[Link] += amount
[Link](f"Deposit: +${amount}")
return True
return False

def withdraw(self, amount):


"""Instance method to withdraw money"""
if 0 < amount <= [Link]:
[Link] -= amount
[Link](f"Withdrawal: -${amount}")
return True
return False

def get_balance(self):
return [Link]

def get_transaction_history(self):
return [Link]

# Usage
account = BankAccount("John Doe", 1000)
[Link](500)
[Link](200)
print(account.get_balance()) # 1300
print(account.get_transaction_history())
# ['Deposit: +$500', 'Withdrawal: -$200']

5. Special Methods (Magic/Dunder Methods) <a


name="special-methods"></a>
Special methods start and end with double underscores. They allow custom behavior for
built-in operations.

[Link] 4/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

Common Special Methods

python

class Vector:
def __init__(self, x, y):
self.x = x
self.y = y

# String representation
def __str__(self):
return f"Vector({self.x}, {self.y})"

def __repr__(self):
return f"Vector(x={self.x}, y={self.y})"

# Arithmetic operations
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)

def __sub__(self, other):


return Vector(self.x - other.x, self.y - other.y)

def __mul__(self, scalar):


return Vector(self.x * scalar, self.y * scalar)

# Comparison operations
def __eq__(self, other):
return self.x == other.x and self.y == other.y

def __lt__(self, other):


return (self.x**2 + self.y**2) < (other.x**2 + other.y**2)

# Length (magnitude)
def __len__(self):
return int((self.x**2 + self.y**2)**0.5)

# Boolean evaluation
def __bool__(self):
return self.x != 0 or self.y != 0

# Usage
v1 = Vector(3, 4)
v2 = Vector(1, 2)

print(v1) # Vector(3, 4)
print(v1 + v2) # Vector(4, 6)

[Link] 5/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

print(v1 * 2) # Vector(6, 8)
print(v1 == v2) # False
print(len(v1)) # 5
print(bool(v1)) # True

More Special Methods

python

class Book:
def __init__(self, title, author, pages):
[Link] = title
[Link] = author
[Link] = pages
self.current_page = 0

def __len__(self):
return [Link]

def __getitem__(self, key):


if key == 'title':
return [Link]
elif key == 'author':
return [Link]
elif key == 'pages':
return [Link]
else:
raise KeyError(f"Book has no attribute '{key}'")

def __iter__(self):
return self

def __next__(self):
if self.current_page < [Link]:
self.current_page += 1
return f"Page {self.current_page}"
else:
self.current_page = 0
raise StopIteration

def __call__(self):
return f"Book: {[Link]} by {[Link]}"

# Usage
book = Book("Python Guide", "John Smith", 300)
print(len(book)) # 300
[Link] 6/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

print(book['title']) # Python Guide


print(book()) # Book: Python Guide by John Smith

# Iteration
for page in book:
if book.current_page > 3: # Show only first 3 pages
break
print(page)
# Page 1
# Page 2
# Page 3

6. Inheritance <a name="inheritance"></a>

Inheritance allows a class to inherit attributes and methods from another class.

Basic Inheritance

python

class Animal:
def __init__(self, name, species):
[Link] = name
[Link] = species

def speak(self):
return "Some generic animal sound"

def move(self):
return f"{[Link]} is moving"

def __str__(self):
return f"{[Link]} the {[Link]}"

class Dog(Animal): # Dog inherits from Animal


def __init__(self, name, breed):
super().__init__(name, "Dog") # Call parent constructor
[Link] = breed

def speak(self): # Method overriding


return "Woof!"

def fetch(self): # New method specific to Dog


return f"{[Link]} is fetching the ball"

[Link] 7/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

class Cat(Animal):
def __init__(self, name, color):
super().__init__(name, "Cat")
[Link] = color

def speak(self):
return "Meow!"

def climb(self):
return f"{[Link]} is climbing a tree"

# Usage
dog = Dog("Buddy", "Golden Retriever")
cat = Cat("Whiskers", "Orange")

print([Link]()) # Woof!
print([Link]()) # Meow!
print([Link]()) # Buddy is moving
print([Link]()) # Whiskers is climbing a tree
print([Link]()) # Buddy is fetching the ball

Multiple Inheritance

python

class Flyable:
def fly(self):
return "I can fly!"

class Swimmable:
def swim(self):
return "I can swim!"

class Duck(Animal, Flyable, Swimmable):


def __init__(self, name):
super().__init__(name, "Duck")

def speak(self):
return "Quack!"

# Usage
duck = Duck("Donald")
print([Link]()) # Quack!
print([Link]()) # I can fly!
print([Link]()) # I can swim!

[Link] 8/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

7. Polymorphism <a name="polymorphism"></a>

Polymorphism allows objects of different classes to be treated as objects of a common super


class.

python

def animal_sounds(animals):
for animal in animals:
print(f"{[Link]}: {[Link]()}")

# Different animals, same interface


animals = [
Dog("Rex", "German Shepherd"),
Cat("Mittens", "Black"),
Duck("Daffy")
]

animal_sounds(animals)
# Rex: Woof!
# Mittens: Meow!
# Daffy: Quack!

8. Encapsulation <a name="encapsulation"></a>

Encapsulation restricts direct access to some components and can prevent accidental
modification.

Name Mangling (Private Attributes)

python

class BankAccount:
def __init__(self, account_holder, balance):
self.account_holder = account_holder
self._balance = balance # Protected attribute (convention)
self.__account_id = 12345 # Private attribute (name mangling)

def get_balance(self):
return self._balance

def _validate_amount(self, amount): # Protected method


return amount > 0

[Link] 9/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

def __generate_statement(self): # Private method


return f"Statement for account {self.__account_id}"

# Usage
account = BankAccount("Alice", 1000)
print(account.account_holder) # Alice
print(account.get_balance()) # 1000

# Can access but shouldn't (convention)


print(account._balance) # 1000

# Cannot access directly (name mangling)


# print(account.__account_id) # AttributeError
# print(account._BankAccount__account_id) # 12345 (but don't do this!)

9. Property Decorators <a name="property-decorators">


</a>
Properties allow controlled access to attributes with getter, setter, and deleter methods.

python

class Temperature:
def __init__(self, celsius=0):
self._celsius = celsius

@property
def celsius(self):
"""Getter for celsius"""
return self._celsius

@[Link]
def celsius(self, value):
"""Setter for celsius with validation"""
if value < -273.15:
raise ValueError("Temperature cannot be below absolute zero!")
self._celsius = value

@property
def fahrenheit(self):
"""Computed property - no setter"""
return (self._celsius * 9/5) + 32

@[Link]
def fahrenheit(self, value):

[Link] 10/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

"""Allow setting via fahrenheit"""


[Link] = (value - 32) * 5/9

# Usage
temp = Temperature(25)
print([Link]) # 25
print([Link]) # 77.0

[Link] = 30
print([Link]) # 86.0

[Link] = 100
print([Link]) # 37.777...

# [Link] = -300 # ValueError: Temperature cannot be below absolute zero!

10. Class Methods and Static Methods <a name="class-


static-methods"></a>

Class Methods

Bound to the class, not the instance

First parameter is cls (class reference)

Can modify class state

Static Methods

Don't have access to cls or self

Utility functions that belong to the class

python

class Date:
def __init__(self, day, month, year):
[Link] = day
[Link] = month
[Link] = year

def __str__(self):
return f"{[Link]}/{[Link]}/{[Link]}"

@classmethod
[Link] 11/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

def from_string(cls, date_string):


"""Alternative constructor from string"""
day, month, year = map(int, date_string.split('/'))
return cls(day, month, year)

@classmethod
def get_current_date(cls):
"""Get current date (example)"""
# In real implementation, you'd use datetime module
return cls(27, 10, 2023)

@staticmethod
def is_valid_date(day, month, year):
"""Check if date is valid"""
if not (1 <= month <= 12):
return False
if not (1 <= day <= 31):
return False
# Simplified validation
return True

@staticmethod
def days_in_month(month, year):
"""Get number of days in month"""
if month in [4, 6, 9, 11]:
return 30
elif month == 2:
return 29 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
else 28
else:
return 31

# Usage
date1 = Date(27, 10, 2023)
date2 = Date.from_string("15/08/2023")
date3 = Date.get_current_date()

print(date1) # 27/10/2023
print(date2) # 15/8/2023
print(date3) # 27/10/2023

print(Date.is_valid_date(31, 4, 2023)) # False (April has 30 days)


print(Date.days_in_month(2, 2020)) # 29 (leap year)

11. Advanced Topics <a name="advanced-topics"></a>


[Link] 12/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

Abstract Base Classes (ABCs)

python

from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod
def area(self):
pass

@abstractmethod
def perimeter(self):
pass

def description(self):
return "This is a shape"

class Rectangle(Shape):
def __init__(self, width, height):
[Link] = width
[Link] = height

def area(self):
return [Link] * [Link]

def perimeter(self):
return 2 * ([Link] + [Link])

class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
return 3.14159 * [Link] ** 2

def perimeter(self):
return 2 * 3.14159 * [Link]

# Usage
# shape = Shape() # TypeError: Can't instantiate abstract class
rect = Rectangle(5, 3)
circle = Circle(4)

print(f"Rectangle area: {[Link]()}") # 15


print(f"Circle perimeter: {[Link]()}") # ~25.13

[Link] 13/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

Data Classes (Python 3.7+)

python

from dataclasses import dataclass


from typing import List

@dataclass
class Person:
name: str
age: int
email: str = "" # Default value
hobbies: List[str] = None

def __post_init__(self):
if [Link] is None:
[Link] = []

def greet(self):
return f"Hello, I'm {[Link]}, {[Link]} years old"

# Usage
person1 = Person("Alice", 30, "alice@[Link]", ["reading", "hiking"])
person2 = Person("Bob", 25)

print(person1) # Person(name='Alice', age=30, email='alice@[Link]', hobbies=


['reading', 'hiking'])
print(person1 == person2) # False
print([Link]()) # Hello, I'm Alice, 30 years old

Metaclasses (Advanced)

python

class Meta(type):
def __new__(cls, name, bases, dct):
# Add a class attribute to all classes using this metaclass
dct['created_by'] = 'MetaClass'
return super().__new__(cls, name, bases, dct)

def __init__(cls, name, bases, dct):


super().__init__(name, bases, dct)
# Register class upon creation
if hasattr(cls, 'registry'):
[Link](cls)

[Link] 14/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

class MyClass(metaclass=Meta):
registry = []

def __init__(self, value):


[Link] = value

# Usage
obj = MyClass(42)
print(obj.created_by) # MetaClass
print([Link]) # [<class '__main__.MyClass'>]

12. Best Practices <a name="best-practices"></a>

1. Follow Naming Conventions

python

# Class names: CamelCase


class BankAccount: pass
class CustomerOrder: pass

# Constants: UPPER_CASE
MAX_SIZE = 100
DEFAULT_TIMEOUT = 30

# Private: _single_leading_underscore
# Strong Private: __double_leading_underscore

2. Use Properties for Attribute Access Control

python

class Person:
def __init__(self, name, age):
self._name = name
self._age = age

@property
def age(self):
return self._age

@[Link]
def age(self, value):

[Link] 15/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

if value < 0:
raise ValueError("Age cannot be negative")
self._age = value

3. Prefer Composition Over Inheritance

python

class Engine:
def start(self):
return "Engine started"

class Wheels:
def rotate(self):
return "Wheels rotating"

class Car:
def __init__(self):
[Link] = Engine()
[Link] = [Wheels() for _ in range(4)]

def drive(self):
results = [[Link]()]
[Link]([Link]() for wheel in [Link])
return results

4. Use super() for Inheritance

python

class Parent:
def __init__(self, name):
[Link] = name

class Child(Parent):
def __init__(self, name, age):
super().__init__(name) # Proper way to call parent constructor
[Link] = age

5. Implement Proper String Representations

python

[Link] 16/22
9/27/25, 7:10 AM Comprehensive Python Classes Tutorial - DeepSeek

class Product:
def __init__(self, name, price):
[Link] = name
[Link] = price

def __str__(self):
return f"{[Link]} - ${[Link]}"

def __repr__(self):
return f"Product(name='{[Link]}', price={[Link]})"

6. Use Type Hints

python

from typing import List, Optional

class ShoppingCart:
def __init__(self, customer_name: str) -> None:
self.customer_name: str = customer_name
[Link]: List[str] = []

def add_item(self, item: str, quantity: int = 1) -> None:


[Link]([item] * quantity)

def get_item_count(self) -> int:


return len([Link])

This comprehensive tutorial covers Python classes from basic to advanced concepts. Practice
each concept with examples to solidify your understanding!

can you convert this in pdf

I can't directly create PDF files, but I can help you convert this tutorial to PDF in several ways:

Method 1: Copy-Paste to Word/Google Docs then Export as


PDF
Steps:

1. Copy the entire tutorial text

2. Paste into Microsoft Word or Google Docs

[Link] 17/22

You might also like