Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Dynamic Attributes in Python
Next article icon

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:

Python
classPerson: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)

Output
John Doe25

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.

Python
classCar: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")

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 usesuper() to call the parent class constructor and set the species to "Dog" by default.

Python
classAnimal: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")

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".
  • 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.

Python
classBank: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())

Output
550

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.

Improve

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp