InPython, 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:
PythonclassPerson:def__init__(self,name,age):self.name=nameself.age=age# instance of the classa=Person("John Doe",25)# Accessing attributesprint(a.name)print(a.age)
Explanation:
- __init__ method takes two parameters, name and age and initializes them for each instance.
- We then create an instance calleda and pass the values "John Doe" and 25 to the constructor.
- We can access the instance's attributes using dot notation, such asa.name anda.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 simpleCar class to represent a car with basic attributes likemake,model and year. We also add a method to simulate driving the car, which increases its mileage.
PythonclassCar:def__init__(self,make,model,year):self.make=makeself.model=modelself.year=yearself.mileage=0# Mileage starts at 0defdrive(self,distance):self.mileage+=distancea=Car("Toyota","Camry",2022)# Car objectprint(f"{a.make}{a.model} ({a.year})")a.drive(100)print(f"Mileage:{a.mileage} miles")
OutputToyota 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 usesuper() to call the parent class constructor and set the species to "Dog" by default.
PythonclassAnimal:def__init__(self,species):self.species=species# Base class attributeclassDog(Animal):def__init__(self,name,age):super().__init__("Dog")# Set species as 'Dog'self.name=nameself.age=agedog=Dog("Buddy",3)# Dog instanceprint(f"{dog.name} is a{dog.species} of age{dog.age} years")
OutputBuddy 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".
- dogobject has aname and age along with inherited species.
Example 3:This example demonstrates encapsulation by usingdoubleunderscores (__) to make the balance attribute private. The class provides methods to deposit, withdraw and view the balance securely.
PythonclassBank:def__init__(self,name,bal=0):self.name=nameself.__bal=baldefdeposit(self,amt):ifamt>0:self.__bal+=amtdefwithdraw(self,amt):if0<amt<=self.__bal:self.__bal-=amtdefget_bal(self):returnself.__balacc=Bank("Alice",500)acc.deposit(200)acc.withdraw(150)print(acc.get_bal())
Explanation:
- __bal attribute is private, meaning it cannot be accessed directly from outside the class.
- methodsdeposit(),withdraw()and get_bal() provide safe access and modification to the balance.
- After depositing 200 and withdrawing 150, the final balance is 550.