In Python, an object is an instance of a class, which acts as a blueprint 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
class Car:
def __init__(self, model, price):
self.model = model
self.price = price
Audi = Car("R8", 100000)
print(Audi.model)
print(Audi.price)
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. When Audi = Car("R8", 100000) is executed, "R8" is assigned to model and 100000 to price. These attributes are accessed via dot notation, like Audi.model and Audi.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
class Car:
def __init__(self, model):
self.model = model
def setprice(self, price):
self.price = price
def getprice(self):
return self.price
Audi = Car("R8")
Audi.setprice(1000000)
print(Audi.getprice())
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 using setprice() and the price is accessed with getprice().
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
class Car:
vehicle = 'Car'
def __init__(self, model, price):
self.model = model
self.price = price
Audi = Car("R8", 100000)
BMW = Car("I8", 10000000)
print(Audi.model, Audi.price)
print(BMW.model, BMW.price)
OutputR8 100000
I8 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) and BMW = Car("I8", 10000000) are executed, the attributes are set and accessed directly, like Audi.model and Audi.price.
Self keyword in Python objects
In Python objects, the self 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
class Test:
def __init__(self, a, b):
self.country = a
self.capital = b
def fun(self):
print("Capital of " + self.country + " is " + self.capital)
x = Test("India", "Delhi")
x.fun()
OutputCapital 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.country and x.capital are 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
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
Audi = Car("Audi", "A6") # creating obj
del Audi # deleting obj
print(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, the del keyword deletes it. Attempting to access Audi.brand afterward results in an error because the object no longer exists.
Related Articles:
Similar Reads
Python Docstrings
When it comes to writing clean, well-documented code, Python developers have a secret weapon at their disposal â docstrings. Docstrings, short for documentation strings, are vital in conveying the purpose and functionality of Python functions, modules, and classes.What are the docstrings in Python?P
10 min read
Python Docstrings
When it comes to writing clean, well-documented code, Python developers have a secret weapon at their disposal â docstrings. Docstrings, short for documentation strings, are vital in conveying the purpose and functionality of Python functions, modules, and classes.What are the docstrings in Python?P
10 min read
Python Modules
Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we c
7 min read
Python Modules
Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we c
7 min read
Python 3 basics
Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.11.0, we can simply call it Python3. Python 3.0 was released in 2008. and is interpreted language i.e it's not compiled and the interpreter will check the code line by line. This article can be used to learn the
10 min read
Python 3 basics
Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.11.0, we can simply call it Python3. Python 3.0 was released in 2008. and is interpreted language i.e it's not compiled and the interpreter will check the code line by line. This article can be used to learn the
10 min read
Python Features
Python is a dynamic, high-level, free open source, and interpreted programming language. It supports object-oriented programming as well as procedural-oriented programming. In Python, we don't need to declare the type of variable because it is a dynamically typed language. For example, x = 10 Here,
5 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Crash Course
If you are aware of programming languages and ready to unlock the power of Python, enter the world of programming with this free Python crash course. This crash course on Python is designed for beginners to master Python's fundamentals in record time! Experienced Python developers developed this fre
7 min read