Creating Instance Objects in Python
In Python, an instance object is an individual object created from a class, which serves as a blueprint defining the attributes (data) and methods (functions) for the object. When we create an object from a class, it is referred to as an instance. Each instance has its own unique data but shares the class's methods. Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# instance of the class
a = Person("John Doe", 25)
# Accessing attributes
print(a.name)
print(a.age)
Output
John Doe 25
Explanation:
- __init__ method takes two parameters, name and age and initializes them for each instance.
- We then create an instance called a and pass the values "John Doe" and 25 to the constructor.
- We can access the instance's attributes using dot notation, such as a.name and a.age.
Syntax of creating instance objects
class ClassName:
def __init__(self, parameters):
# constructor code here
# initialize instance variables
# Create an instance of the class
instance_object = ClassName(parameters)
- ClassName: The name of the class.
- __init__: The constructor method, responsible for initializing the instance.
- self: A reference to the instance itself.
- parameters: Any data that needs to initialize the instance.
When you instantiate a class, the __init__ method is called to initialize the object’s attributes.
Examples of creating instance object
Example 1: In this example, we define a simple Car class to represent a car with basic attributes like make, model and year. We also add a method to simulate driving the car, which increases its mileage.
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.mileage = 0 # Mileage starts at 0
def drive(self, distance):
self.mileage += distance
a = Car("Toyota", "Camry", 2022) # Car object
print(f"{a.make} {a.model} ({a.year})")
a.drive(100)
print(f"Mileage: {a.mileage} miles")
Output
Toyota Camry (2022) Mileage: 100 miles
Explanation:
- Car class has attributes for make, model, year and mileage.
- drive() method increases the mileage by the given distance.
- We create an instance a of the Car class and drive it for 100 miles.
Example 2: In this example, we create a base class Animal and a derived class Dog. We use super() to call the parent class constructor and set the species to "Dog" by default.
class Animal:
def __init__(self, species):
self.species = species # Base class attribute
class Dog(Animal):
def __init__(self, name, age):
super().__init__("Dog") # Set species as 'Dog'
self.name = name
self.age = age
dog = Dog("Buddy", 3) # Dog instance
print(f"{dog.name} is a {dog.species} of age {dog.age} years")
Output
Buddy is a Dog of age 3 years
Explanation:
- Animal is a base class with one attribute species.
- Dog inherits from Animal and uses super() to set species as "Dog".
- dog object has a name and age along with inherited species.
Example 3: This example demonstrates encapsulation by using double underscores (__) to make the balance attribute private. The class provides methods to deposit, withdraw and view the balance securely.
class Bank:
def __init__(self, name, bal=0):
self.name = name
self.__bal = bal
def deposit(self, amt):
if amt > 0: self.__bal += amt
def withdraw(self, amt):
if 0 < amt <= self.__bal: self.__bal -= amt
def get_bal(self):
return self.__bal
acc = Bank("Alice", 500)
acc.deposit(200)
acc.withdraw(150)
print(acc.get_bal())
Output
550
Explanation:
- __bal attribute is private, meaning it cannot be accessed directly from outside the class.
- methods deposit(), withdraw() and get_bal() provide safe access and modification to the balance.
- After depositing 200 and withdrawing 150, the final balance is 550.