CLASS & OBJECT IN PYTHON

machine learning from scratch
CLASS

Class is a core concept in a style of programming known as Object-Oriented Programming. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class also describes object behavior.

Consider the Class of motorcycles. There may be many motorcycles with different names and brands but all of them will share some common properties like all of them will have 2 wheels, Speed Limit, Mileage range, etc. So, Motorcycle is the class and wheels, speed limits, mileage are their properties. 

In many cases classes are used to represent real-world entities. Classes actually act as templates that are used to construct instances or examples of a class of things. An instance or object is therefore an example of a class. 

We define classes by using the class keyword. In Python, a class definition has the following format:

class nameOfClass:
       __init__
       attributes
       methods

Let’s create a class with the class name Smartphone. Suppose we have two objects Samsung and Apple that belong to the class of smartphones. Let objects’ attributes are size, price, and methods be buy().

 >>> class smartphone:
        #instance attributes
        next = " one method of instance attribute"
        def __init__(self, name, size, price):
                self.name = name
                self.size = size
                self.price = price
        
        #instance method
        def buy(self, location):
                return (‘Apple sell market is in’, location)

There is also a special method defined called __init__. This is an initializer also known as a constructor) for the class.

OBJECT

An Object is an instance of a particular class or subclass with the class’s own methods or procedures and data variables. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated. Object determines the behavior of the class. 

Variables that belong to an object or class are referred to as fields. Objects can also have functionality by using functions that belong to a class. Such functions are called methods of the class. Another way to say this is that a method is an action that an object is able to perform. The fields and methods can be referred to as the attributes of that class.

The class creates a user-defined data structure, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class and passing in the values to be used for the parameters of the initialization method (with the exception of the first parameter self which is provided automatically by Python). 

For example, the following creates two instances of the class smartphone:

>>> s = smartphone("Samsung","M", 300)
>>> a = smartphone("apple","L", 900)

We can create multiple different objects that are of the same class. However, each object contains independent copies of the variables defined in the class. In the above example, we have created two objects s & a under the same class smartphone.

The variable s holds a reference to the instance or object of the class smartphone whose attributes hold the values ‘Samsung’ (for the name attribute) and ‘M’ (for size attribute) and  300 (for the price attribute). In turn variable a holds a reference to the instance or object of the class smartphone whose attributes hold the values ‘apple’ (for the name attribute) and ‘L’ (for size attribute) and  900 (for the price attribute). The two variables s and a reference separate instances or examples of the class smartphone.

ACCESSING ATTRIBUTES

We can access the attributes held by s and a using what is known as the dot notation.  Let’s go with an example:

>>> print (s.name,"costs",s.price,"$")
>>> print (a.buy("New York"))
 
Output:
Samsung costs 300$
Apple sell market is in New York
CONSTRUCTOR

Constructor is used for initializing the instance members when we create the object of a class. A constructor always has a name init and the name init is prefixed and suffixed with a double underscore(_ _). In the above example, we have an instance variable name, size, price which we are initializing in the constructor.

-----------SYNTAX-------------
def __init__(self):
 #constructor body

All classes have a function called init(), which is always executed when the class is being initiated. We use built-in init() function to assign values to object properties, or other operations that are necessary to do when the object is being created.

>>> class Dog:                                      #creating class
        def __init__(self, name):         # constructor
                     self.name = name
>>> x = Dog("votey")
>>> print (x.name )
 
Output:
votey

Sometimes, we don’t declare a constructor. In such condition, the default constructor is implicitly injected by python during program compilation, which is an empty default constructor and looks like:

>>> def __init__(self): 
             # no body, does nothing

Generally, there are two types of constructors on the basis of parameters.

  1. default constructor: without any parameters
  2. parameterized constructor: with parameters
# default constructor
>>> class default():
        def __init__(self):
                self.num = 30
>>> x = default ()
>>> print (x.num)
 
Output: 30
# parameterized constructor
>>> class default():
        def __init__(self,num):
                self.num = num
>>> x = default (50)
>>> print (x.num)
 
Output: 50
SELF

Self in the constructor is used to access variables that belong to the class and self is defined as the reference to the current instance of the class. We need not give the same name self, that means we can name it like variables but it has to be the first parameter of any function in the class. This is illustrated in the example below where in place of self we have used diwas.

>>> class john:                                      #creating class
        def __init__(diwas, name):         # constructor
                diwas.name = name
>>> x = john("votey")
>>> print (x.name )
DESTRUCTOR

del() method is known as a destructor method in Python. Destructors are called when an object needs to be destroyed. Destructors are used to delete unneeded objects to free the memory space.

# syntax of destructor
>>> def __del__(self):
           # body of destructor
>>> class Point:
        def __init__( self):
                self.x = 3
                self.y = 4
        def __del__(self):
                class_name = self.__class__.__name__
                print ( " object is now destroyed")
>>> obj1 = Point()
>>> del obj1
 
Output:
object is now destroyed

This page is contributed by Diwas. If you like AIHUB and would like to contribute, you can also write an article & mail your article to  itsaihub@gmail.com . See your articles appearing on AI HUB platform and help other AI Enthusiast.

About Diwas

🚀 I'm Diwas Pandey, a Computer Engineer with an unyielding passion for Artificial Intelligence, currently pursuing a Master's in Computer Science at Washington State University, USA. As a dedicated blogger at AIHUBPROJECTS.COM, I share insights into the cutting-edge developments in AI, and as a Freelancer, I leverage my technical expertise to craft innovative solutions. Join me in bridging the gap between technology and healthcare as we shape a brighter future together! 🌍🤖🔬

View all posts by Diwas →

3 Comments on “CLASS & OBJECT IN PYTHON”

  1. An intriguing discussion is definitely worth comment.
    I do believe that you need to write more on this issue,
    it may not be a taboo subject but generally folks don’t talk about these
    topics. To the next! Cheers!! adreamoftrains web hosting reviews

Leave a Reply

Your email address will not be published. Required fields are marked *