Python Classes and Objects Examples
New to Python and Object-Oriented Programming (OOP)? No worries! This guide will walk you through easy-to-follow examples to help you understand the basics of classes and objects. You'll also learn how to work with methods, attributes, inheritance, and more—step by step!
1. Basic class and object
1. Basic class and object
python
# Example 1: Simple class
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello, my name is", self.name)
p = Person("Alice")
p.greet()
# Example 1: Simple class
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello, my name is", self.name)
p = Person("Alice")
p.greet()
2. Class with multiple attributes
2. Class with multiple attributes
python
# Example 2: Class with multiple attributes
class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year
def info(self):
print(f"Brand: {self.brand}, Year: {self.year}")
c = Car("Toyota", 2020)
c.info()
# Example 2: Class with multiple attributes
class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year
def info(self):
print(f"Brand: {self.brand}, Year: {self.year}")
c = Car("Toyota", 2020)
c.info()
3. Default attribute values
3. Default attribute values
python
# Example 3: Default values
class Animal:
def __init__(self, species="Dog"):
self.species = species
def show(self):
print("Species:", self.species)
a = Animal()
a.show()
# Example 3: Default values
class Animal:
def __init__(self, species="Dog"):
self.species = species
def show(self):
print("Species:", self.species)
a = Animal()
a.show()
4. Object methods modifying attributes
4. Object methods modifying attributes
python
# Example 4: Method modifies attributes
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
c = Counter()
c.increment()
print("Count:", c.count)
# Example 4: Method modifies attributes
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
c = Counter()
c.increment()
print("Count:", c.count)
5. Inheritance example
5. Inheritance example
python
# Example 5: Inheritance
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Woof!")
d = Dog()
d.speak()
d.bark()
# Example 5: Inheritance
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Woof!")
d = Dog()
d.speak()
d.bark()
6. Method overriding
6. Method overriding
python
# Example 6: Overriding method
class Parent:
def greet(self):
print("Hello from Parent")
class Child(Parent):
def greet(self):
print("Hello from Child")
c = Child()
c.greet()
# Example 6: Overriding method
class Parent:
def greet(self):
print("Hello from Parent")
class Child(Parent):
def greet(self):
print("Hello from Child")
c = Child()
c.greet()
7. Using isinstance() and type()
7. Using isinstance() and type()
python
# Example 7: isinstance and type
class User:
pass
u = User()
print(isinstance(u, User)) # True
print(type(u)) # <class '__main__.User'>
# Example 7: isinstance and type
class User:
pass
u = User()
print(isinstance(u, User)) # True
print(type(u)) # <class '__main__.User'>
8. Class variables vs instance variables
8. Class variables vs instance variables
python
# Example 8: Class vs instance variables
class Book:
category = "Fiction" # Class variable
def __init__(self, title):
self.title = title # Instance variable
b1 = Book("1984")
b2 = Book("Animal Farm")
print(b1.category, b1.title)
print(b2.category, b2.title)
# Example 8: Class vs instance variables
class Book:
category = "Fiction" # Class variable
def __init__(self, title):
self.title = title # Instance variable
b1 = Book("1984")
b2 = Book("Animal Farm")
print(b1.category, b1.title)
print(b2.category, b2.title)
9. Private attributes (name mangling)
9. Private attributes (name mangling)
python
# Example 9: Private attribute
class Secret:
def __init__(self):
self.__hidden = "This is private"
s = Secret()
print(s._Secret__hidden) # Accessing private var
# Example 9: Private attribute
class Secret:
def __init__(self):
self.__hidden = "This is private"
s = Secret()
print(s._Secret__hidden) # Accessing private var
10. A simple class-based menu
10. A simple class-based menu
python
# Example 10: Menu with class
class Menu:
def display(self):
print("1. Start")
print("2. Exit")
def choose(self, option):
if option == 1:
print("Starting...")
elif option == 2:
print("Exiting...")
else:
print("Invalid option")
m = Menu()
m.display()
m.choose(1)
# Example 10: Menu with class
class Menu:
def display(self):
print("1. Start")
print("2. Exit")
def choose(self, option):
if option == 1:
print("Starting...")
elif option == 2:
print("Exiting...")
else:
print("Invalid option")
m = Menu()
m.display()
m.choose(1)
11. Class with a method that takes parameters
11. Class with a method that takes parameters
python
# Example 11: Method with parameters
class Calculator:
def add(self, a, b):
return a + b
c = Calculator()
print("Sum:", c.add(3, 5))
# Example 11: Method with parameters
class Calculator:
def add(self, a, b):
return a + b
c = Calculator()
print("Sum:", c.add(3, 5))
12. Using @classmethod
12. Using @classmethod
python
# Example 12: Class method
class Student:
school = "Green High"
def __init__(self, name):
self.name = name
@classmethod
def get_school(cls):
return cls.school
print(Student.get_school())
# Example 12: Class method
class Student:
school = "Green High"
def __init__(self, name):
self.name = name
@classmethod
def get_school(cls):
return cls.school
print(Student.get_school())
13. Using @staticmethod
13. Using @staticmethod
python
# Example 13: Static method
class MathTools:
@staticmethod
def square(n):
return n * n
print(MathTools.square(4))
# Example 13: Static method
class MathTools:
@staticmethod
def square(n):
return n * n
print(MathTools.square(4))
14. Simple encapsulation with getters/setters
14. Simple encapsulation with getters/setters
python
# Example 14: Encapsulation
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
acct = BankAccount(100)
acct.deposit(50)
print("Balance:", acct.get_balance())
# Example 14: Encapsulation
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
acct = BankAccount(100)
acct.deposit(50)
print("Balance:", acct.get_balance())
15. Object composition example
15. Object composition example
python
# Example 15: Composition
class Engine:
def start(self):
print("Engine started")
class Car:
def __init__(self):
self.engine = Engine()
def drive(self):
self.engine.start()
print("Car is moving")
c = Car()
c.drive()
# Example 15: Composition
class Engine:
def start(self):
print("Engine started")
class Car:
def __init__(self):
self.engine = Engine()
def drive(self):
self.engine.start()
print("Car is moving")
c = Car()
c.drive()
16. Counting instances with class variable
16. Counting instances with class variable
python
# Example 16: Count objects
class Counter:
count = 0
def __init__(self):
Counter.count += 1
print("Initial:", Counter.count)
a = Counter()
b = Counter()
print("After creation:", Counter.count)
# Example 16: Count objects
class Counter:
count = 0
def __init__(self):
Counter.count += 1
print("Initial:", Counter.count)
a = Counter()
b = Counter()
print("After creation:", Counter.count)
17. Simple Inheritance Example
17. Simple Inheritance Example
python
# Example 17: Basic inheritance example
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Woof!")
dog = Dog()
dog.speak() # Output: Woof!
# Example 17: Basic inheritance example
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Woof!")
dog = Dog()
dog.speak() # Output: Woof!
18. Hiding data with name mangling
18. Hiding data with name mangling
python
# Example 18: Data hiding
class Account:
def __init__(self):
self.__balance = 100
def get_balance(self):
return self.__balance
acct = Account()
print(acct.get_balance())
# print(acct.__balance) # AttributeError
print(acct._Account__balance)
# Example 18: Data hiding
class Account:
def __init__(self):
self.__balance = 100
def get_balance(self):
return self.__balance
acct = Account()
print(acct.get_balance())
# print(acct.__balance) # AttributeError
print(acct._Account__balance)
19. Class inheritance with super()
19. Class inheritance with super()
python
# Example 19: super() in inheritance
class Animal:
def __init__(self, species):
self.species = species
class Dog(Animal):
def __init__(self, name):
super().__init__("Dog")
self.name = name
d = Dog("Max")
print(d.species, d.name)
# Example 19: super() in inheritance
class Animal:
def __init__(self, species):
self.species = species
class Dog(Animal):
def __init__(self, name):
super().__init__("Dog")
self.name = name
d = Dog("Max")
print(d.species, d.name)
20. Inheritance with Constructor Overriding
20. Inheritance with Constructor Overriding
python
# Example 20: Constructor overriding in inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def speak(self):
print(f"{self.name} barks")
dog = Dog("Buddy", "Golden Retriever")
dog.speak() # Output: Buddy barks
# Example 20: Constructor overriding in inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def speak(self):
print(f"{self.name} barks")
dog = Dog("Buddy", "Golden Retriever")
dog.speak() # Output: Buddy barks
21. Using Encapsulation with Getters and Setters
21. Using Encapsulation with Getters and Setters
python
# Example 21: Encapsulation with getters and setters
class Person:
def __init__(self, name, age):
self._name = name # Protected attribute
self._age = age # Protected attribute
# Getter method for name
@property
def name(self):
return self._name
# Setter method for name
@name.setter
def name(self, value):
self._name = value
# Getter method for age
@property
def age(self):
return self._age
# Setter method for age
@age.setter
def age(self, value):
if value < 0:
print("Age cannot be negative")
else:
self._age = value
p = Person("Alice", 30)
print(p.name) # Output: Alice
p.age = -5 # Output: Age cannot be negative
# Example 21: Encapsulation with getters and setters
class Person:
def __init__(self, name, age):
self._name = name # Protected attribute
self._age = age # Protected attribute
# Getter method for name
@property
def name(self):
return self._name
# Setter method for name
@name.setter
def name(self, value):
self._name = value
# Getter method for age
@property
def age(self):
return self._age
# Setter method for age
@age.setter
def age(self, value):
if value < 0:
print("Age cannot be negative")
else:
self._age = value
p = Person("Alice", 30)
print(p.name) # Output: Alice
p.age = -5 # Output: Age cannot be negative
22. Multiple Inheritance Example
22. Multiple Inheritance Example
python
# Example 22: Multiple inheritance
class Father:
def speak(self):
print("Father speaks")
class Mother:
def speak(self):
print("Mother speaks")
class Child(Father, Mother):
def greet(self):
print("Hello!")
child = Child()
child.speak() # Output: Father speaks
child.greet() # Output: Hello!
# Example 22: Multiple inheritance
class Father:
def speak(self):
print("Father speaks")
class Mother:
def speak(self):
print("Mother speaks")
class Child(Father, Mother):
def greet(self):
print("Hello!")
child = Child()
child.speak() # Output: Father speaks
child.greet() # Output: Hello!
23. Using Private Attributes and Methods
23. Using Private Attributes and Methods
python
# Example 23: Using private attributes
class Account:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
else:
print("Deposit amount must be positive")
def get_balance(self):
return self.__balance
acct = Account(1000)
acct.deposit(500)
print(acct.get_balance()) # Output: 1500
# Example 23: Using private attributes
class Account:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
else:
print("Deposit amount must be positive")
def get_balance(self):
return self.__balance
acct = Account(1000)
acct.deposit(500)
print(acct.get_balance()) # Output: 1500
24. Inheritance with Method Overriding
24. Inheritance with Method Overriding
python
# Example 24: Method overriding in inheritance
class Vehicle:
def start(self):
print("Starting vehicle")
class Car(Vehicle):
def start(self):
print("Starting car engine")
car = Car()
car.start() # Output: Starting car engine
# Example 24: Method overriding in inheritance
class Vehicle:
def start(self):
print("Starting vehicle")
class Car(Vehicle):
def start(self):
print("Starting car engine")
car = Car()
car.start() # Output: Starting car engine
25. Inheritance with `super()`
25. Inheritance with `super()`
python
# Example 25: Using 'super()' in inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Calling the parent class constructor
self.breed = breed
dog = Dog("Buddy", "Labrador")
dog.speak() # Output: Buddy makes a sound
# Example 25: Using 'super()' in inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Calling the parent class constructor
self.breed = breed
dog = Dog("Buddy", "Labrador")
dog.speak() # Output: Buddy makes a sound
26. Class with Private and Protected Members
26. Class with Private and Protected Members
python
# Example 26: Private and protected members
class Car:
def __init__(self, make, model):
self._make = make # Protected attribute
self.__model = model # Private attribute
def display(self):
print(f"Make: {self._make}, Model: {self.__model}")
car = Car("abc_maker", "abc_model")
car.display() # Output: Make: abc_maker, Model: abc_model
# Example 26: Private and protected members
class Car:
def __init__(self, make, model):
self._make = make # Protected attribute
self.__model = model # Private attribute
def display(self):
print(f"Make: {self._make}, Model: {self.__model}")
car = Car("abc_maker", "abc_model")
car.display() # Output: Make: abc_maker, Model: abc_model
27. Abstract Base Class with Encapsulation
27. Abstract Base Class with Encapsulation
python
# Example 27: Abstract Base Class with encapsulation
from abc import ABC, abstractmethod
class Shape(ABC):
def __init__(self, color):
self._color = color # Protected attribute
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
self.__radius = radius # Private attribute
def area(self):
return 3.14 * (self.__radius ** 2)
circle = Circle("Red", 5)
print(circle.area()) # Output: 78.5
# Example 27: Abstract Base Class with encapsulation
from abc import ABC, abstractmethod
class Shape(ABC):
def __init__(self, color):
self._color = color # Protected attribute
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
self.__radius = radius # Private attribute
def area(self):
return 3.14 * (self.__radius ** 2)
circle = Circle("Red", 5)
print(circle.area()) # Output: 78.5
28. Method Overloading Simulation Using Encapsulation
28. Method Overloading Simulation Using Encapsulation
python
# Example 28: Method overloading simulation using encapsulation
class Calculator:
def add(self, *args):
result = 0
for num in args:
result += num
return result
calc = Calculator()
print(calc.add(2, 3)) # Output: 5
print(calc.add(1, 2, 3, 4)) # Output: 10
# Example 28: Method overloading simulation using encapsulation
class Calculator:
def add(self, *args):
result = 0
for num in args:
result += num
return result
calc = Calculator()
print(calc.add(2, 3)) # Output: 5
print(calc.add(1, 2, 3, 4)) # Output: 10
Keep Practicing Python
Great job learning the basics! To become truly comfortable with Python, the key is practice. Try solving coding challenges, building small projects, and experimenting with different Python concepts beyond OOP, such as functions, loops, and data structures. The more you practice, the more confident you'll become in using Python for real-world applications!