Open In App

Python object

Last Updated : 21 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. Python is an object-oriented programming language that stresses objects i.e. it mainly emphasizes functions. Python Objects are basically an encapsulation of data variables and methods acting on that data into a single entity.

Note: For more information, Python Classes and Objects

Understanding of Python Object

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.

Syntax: 

obj = MyClass()
print(obj.x)

Instance defining represent memory allocation necessary for storing the actual data of variables. Each time when you create an object of class a copy of each data variable defined in that class is created. In simple language, we can state that each object of a class has its own copy of data members defined in that class. 

Creating a Python Object

Working of the Program: Audi = Cars()

  • A block of memory is allocated on the heap. The size of memory allocated is decided by the attributes and methods available in that class(Cars).
  • After the memory block is allocated, the special method __init__() is called internally. Initial data is stored in the variables through this method.
  • The location of the allocated memory address of the instance is returned to the object(Cars).
  • The memory location is passed to self.

Python3




class Cars:
  def __init__(self, m, p):
    self.model = m
    self.price = p
 
Audi = Cars("R8", 100000)
 
print(Audi.model)
print(Audi.price)


Output: 

R8
100000

Accessing Class Member Using Object:

Variables and methods of a class are accessible by using class objects or instances in Python.

Syntax: 

obj_name.var_name
Audi.model

obj_name.method_name()
Audi.ShowModel();

obj_name.method_name(parameter_list)
Audi.ShowModel(100);

Example 1:  

Python3




# Python program to create instance
# variables inside methods
     
class Car:
         
    # Class Variable
    vehicle = 'car'   
         
    # The init method or constructor
    def __init__(self, model):
             
        # Instance Variable
        self.model = model            
     
    # Adds an instance variable
    def setprice(self, price):
        self.price = price
         
    # Retrieves instance variable    
    def getprice(self):    
        return self.price    
     
# Driver Code
Audi = Car("R8")
Audi.setprice(1000000)
print(Audi.getprice())


Output: 

1000000

Example 2:

Python3




class Car:
     
    # Class Variable
    vehicle = 'Car'           
     
    # The init method or constructor
    def __init__(self, model, price):
     
        # Instance Variable    
        self.model = model
        self.price = price        
     
# Objects of class
Audi = Car("R8", 100000)
BMW = Car("I8", 10000000)
 
print('Audi details:')
print('Audi is a', Audi.vehicle)
print('Model: ', Audi.model)
print('price: ', Audi.price)
 
print('\n BMW details:')
print('BMW is a', BMW.vehicle)
print('Model: ', BMW.model)
print('Color: ', BMW.price)
 
# Class variables can be
# accessed using class
# name also
print("\nAccessing class variable using class name")
print(Car.vehicle)  
 
# or
print(Audi.vehicle)  
 
# or
print(BMW.vehicle)  


Output: 

Audi details:
Audi is a Car
Model:  R8
price:  100000

 BMW details:
BMW is a Car
Model:  I8
Color:  10000000

Accessing class variable using class name
Car
Car
Car

Self Variable:

SELF is a default variable that contains the memory address of the current object in Python. Instance variables and methods can be referred to by the self-variable. When the object of a class is created, the memory location of the object is contained by its object name. This memory location is passed to the SELF internally, as SELF knows the memory address of the object, so the variable and method of an object are accessible. The first argument to any object method is SELF because the first argument is always object reference. This process takes place automatically whether you call it or not.

Example:

Python3




class Test:
  def __init__(Myobject, a, b):
    Myobject.country = a
    Myobject.capital = b
 
  def myfunc(abc):
    print("Capital of  " + abc.country +" is:"+abc.capital)
 
x = Test("India", "Delhi")
x.myfunc()


Output: 

Capital of India is: Delhi

Note: For more information, refer to self in the Python class

Deleting an Object in Python:

Python Object property can be deleted by using the del keyword:

Syntax:  

del obj_name.property

objects also can be deleted by del keyword:

Syntax: 

del obj_name 


Similar Reads

Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
Prerequisite: Object-Oriented Programming in Python | Set 1 (Class, Object and Members) Data hiding In Python, we use double underscore (Or __) before the attributes name and those attributes will not be directly visible outside. Python Code class MyClass: # Hidden member of MyClass __hiddenVariable = 0 # A member method that changes # __hiddenVari
3 min read
Object Detection vs Object Recognition vs Image Segmentation
Object Recognition: Object recognition is the technique of identifying the object present in images and videos. It is one of the most important applications of machine learning and deep learning. The goal of this field is to teach machines to understand (recognize) the content of an image just like humans do. Object Recognition Using Machine Learni
5 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
OOP in Python | Set 3 (Inheritance, examples of object, issubclass and super)
We have discussed following topics on Object Oriented Programming in Python Object Oriented Programming in Python | set-1 Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing) In this article, Inheritance is introduced. One of the major advantages of Object Oriented Programming is re-use. Inheritance is one of the mechanis
4 min read
Find the Solidity and Equivalent Diameter of an Image Object Using OpenCV Python
In this article, we will see how we can find the solidity and the equivalent diameter of an object present in an image with help of Python OpenCV. Function to Find Solidity The solidity of an image is the measurement of the overall concavity of a particle. We can define the solidity of an object as the ratio of the contour area to its convex hull a
4 min read
Python Object Comparison : "is" vs "=="
Both "is" and "==" are used for object comparison in Python. The operator "==" compares values of two objects, while "is" checks if two objects are same (In other words two references to same object). # Python program to demonstrate working of # "==" # Two different objects having same values x1 = [10, 20, 30] x2 = [10, 20, 30] # Comparis
2 min read
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 inherit from the Object class. Syntax : obj = obje
3 min read
Python | Convert dictionary object into string
The dictionary is an important container and is used almost in every code of day-to-day programming as well as web development with Python. The more it is used, the more is the requirement to master it and hence it's necessary to learn about them. Input: { "testname" : "akshat","test2name" : "manjeet","test3name" : "nikhil"}Output: {"testname": "ak
3 min read
Python | Matplotlib Sub plotting using object oriented API
Plotting using Object Oriented(OO) API in matplotlib is an easy approach to plot graphs and other data visualization methods. The simple syntax to create the class and object for sub-plotting is - class_name, object_name = matplotlib.pyplot.subplots('no_of_rows', 'no_of_columns') Let's take some examples to make it more clear. Example #1: # importi
2 min read
Python | Ways to convert string to json object
In this article, we will see different ways to convert string to JSON in Python this process is called serialization. JSON module provides functions for encoding (serializing) Python objects into JSON strings and decoding (deserializing) JSON strings into Python objects. Encoding (Serializing) JSON: If you have a Python object and want to convert i
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg