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:
[GFGTABS]
Python
class Car:
def __init__(self, model, price):
self.model = model
self.price = price
Audi = Car("R8", 100000)
print(Audi.model)
print(Audi.price)
[/GFGTABS]
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.
[GFGTABS]
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())
[/GFGTABS]
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.
[GFGTABS]
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)
[/GFGTABS]
Output
R8 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:
[GFGTABS]
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()
[/GFGTABS]
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.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:
[GFGTABS]
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)
[/GFGTABS]
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 object() method
The Python object() function returns the empty object, and the Python object takes no parameters. Syntax of Python object() For versions of Python 3.x, the default situation. The base class for all classes, including user-defined ones, is the Python object class. As a result, in Python, all classes
3 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
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 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 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
Python Introduction
Python is a widely used high-level, interpreted programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines o
5 min read
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
11 min read
Python List Exercise
List OperationsAccess List ItemChange List itemReplace Values in a List in PythonAppend Items to a listInsert Items to a listExtend Items to a listRemove Item from a listClear entire listBasic List programsMaximum of two numbersWays to find length of listMinimum of two numbersTo interchange first an
3 min read
Python vs Cpython
Python is a high-level, interpreted programming language favored for its readability and versatility. It's widely used in web development, data science, machine learning, scripting, and more. However, Cpython is the default and most widely used implementation of the Python language. It's written in
4 min read
Python Object Comparison : "is" vs "=="
In Python, both is and == are used for comparison, but they serve different purposes: == (Equality Operator) â Compares values of two objects.is (Identity Operator) â Compares memory location of two objects.[GFGTABS] Python a = [1,2,3] b = [1,2,3] print(a == b) print(a is b) [/GFGTABS]OutputTrue Fal
2 min read