Movatterモバイル変換


[0]ホーム

URL:


Open In App

In Python, an object is an instance of a class, which acts as ablueprint for creating objects. Each object contains data (variables) and methods to operate on that data. Python is object-oriented, meaning it focuses on objects and their interactions. For a better understanding of the concept of objects in Python. Let's consider an example, many of you have played CLASH OF CLANS, So let's assume base layout as the class which contains all the buildings, defenses, resources, etc. Based on these descriptions we make a village, here the village is the object in Python.

Creating an object

When creating an object from a class, we use a special method called the constructor, defined as __init__(), to initialize the object's attributes.Example:

Python
classCar:def__init__(self,model,price):self.model=modelself.price=priceAudi=Car("R8",100000)print(Audi.model)print(Audi.price)

Output
R8100000

Explanation: Car class defines a blueprint for car objects. The __init__()constructor initializes the model and price attributes, using self to refer to the current object. WhenAudi = Car("R8", 100000)is executed, "R8" is assigned to model and 100000 to price. These attributes are accessed via dot notation, likeAudi.model andAudi.price.

Accessing class members

In Python, you can access both instance variables and methods of a class using an object. Instance variables are unique to each object, while methods define the behavior of the objects. Below are examples demonstrating how to access and interact with class members:

Example 1: In this example, we use methods to access and modify the car's attributes.

Python
classCar:def__init__(self,model):self.model=modeldefsetprice(self,price):self.price=pricedefgetprice(self):returnself.priceAudi=Car("R8")Audi.setprice(1000000)print(Audi.getprice())

Output
1000000

Explanation: Car class defines a blueprint for car objects with a constructor (__init__()) to initialize the model attribute. The setprice() method assigns a price and getprice() retrieves it. When Audi = Car("R8") is executed, the model is set to "R8", the price is set usingsetprice() and the price is accessed withgetprice().

Example 2: In this example, we create multiple car objects and access the model and price attributes directly using the objects, without the need for methods.

Python
classCar:vehicle='Car'def__init__(self,model,price):self.model=modelself.price=priceAudi=Car("R8",100000)BMW=Car("I8",10000000)print(Audi.model,Audi.price)print(BMW.model,BMW.price)

Output
R8 100000I8 10000000

Explanation: Car class defines a blueprint with a class variable vehicle and a constructor to initialize model and price. When Audi = Car("R8", 100000) andBMW = Car("I8", 10000000) are executed, the attributes are set and accessed directly, likeAudi.model andAudi.price.

Self keyword in Python objects

In Python objects, theself keyword represents the current instance of the class. It is automatically passed to instance methods and is used to access and modify the object's own attributes and methods. By using self, each object can maintain its own separate state, ensuring that operations are performed on the correct instance.Example:

Python
classTest:def__init__(self,a,b):self.country=aself.capital=bdeffun(self):print("Capital of "+self.country+" is "+self.capital)x=Test("India","Delhi")x.fun()

Output
Capital of India isDelhi

Explanation: Test class uses the__init__()constructor to initialize the country and capital attributes with self. When x is created with "India" and "Delhi", x.countryandx.capitalare set. The fun()method then accesses these attributes via self .

Deleting an object

You can delete objects, variables or object properties using the del keyword. This removes the reference to the object or attribute from memory, allowing Python's garbage collector to reclaim the memory if no other references exist. Example:

Python
classCar:def__init__(self,brand,model):self.brand=brandself.model=modelAudi=Car("Audi","A6")# creating objdelAudi# deleting objprint(Audi.brand)

Output

Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 10, in <module>
print(Audi.brand)
^^^^
NameError: name 'Audi' is not defined

Explanation: After creating the Audi object, thedel keyword deletes it. Attempting to accessAudi.brand afterward results in an error because the object no longer exists.

Related Articles:


Improve
Improve

Explore

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