The concept of Objects and Classes together comes under the umbrella of OOP also known as Object- Oriented Programming. OOP is therefore, a method to structure a set of instructions (a program) by encapsulating related behaviors and similar properties into objects. It is to note that unlike an emphasis on functions as in procedure programming, the main emphasis is on Objects in OOP. In this tutorial, therefore, we take on the topic Object Class in Python.

Object Oriented Programming

Objects are the various integrants of a system. One can then, think of a program to be a factory or an assembly line. Now, at each step of the assembly line, an integrant is there to process some materials. Thereby, finally ending in culmination of the transformation of the raw materials into a finished product.

Object Class in Python

Conceptually, thus, an object contains data, equivalent to the raw material in the assembly line, and behavior, subsequently equivalent to the action performed at each level by the integrants.

As an example, we have a car object with attributes like a brand, model, and shape and behaviors such as mileage, speed, and engine capacity.

Object Class in Python

Objects and Classes

Practically, an object is a collection of data (variables), which are essentially the attributes, and methods (functions) that act on those data, which is essentially the behavior. Likewise, generally, a class is a template or a blueprint for an object.

Take the examples of building a house. Here, the class is the blueprint (sketch, prototype) of the house. It contains the various details like doors, windows and floors. On the basis of these attributes, a house is build or instantiate. Thus, the particular house being built is the object or the instance of the class. Any number of house having peculiar characteristics can be build from the same blueprint or class of the House.

Take another example, the dog class specifies that a dog has attributes like Name, Age, Color and Breed. So, for that, a particular dog named Tommy, Age – 4years and breed – Labrador, is an instance of the dog class. Note, that there can be many objects of the same class Dog.

Another example, can be the class “Drink” where Tea, Coffee and Juice are the various Instances or Objects of the same class, having attributes like name, type, color, price and behaviors like fizziness, etc.

Defining a Class

A definition of the class starts with keyword of the same name, “class” which is followed by the name of the class and a colon. Lets proceed to see an example class as shown below :

class Person:
    pass

The body of the Person class just contains a single ‘pass’ statement as of now. The pass keyword is generally used to indicate a placeholder suggesting the location where the code goes after entering the class construct.

For general naming conventions, check out my previous post.

Now, lets proceed with defining some properties of the “Person” class. We can describe various properties like : name, age, height, weight, and color. To start of lets just use name and age.

The properties that all “Person” ojects shall have is defined in a method called .__init__() Every moment, when a new Person instance is built, the .__init__() construct sets the initial state of the object by assigning the values to the various properties of the object. That is, .__init__() initializes each new instance or object of the class.

One can administer as many number of parameters to .__init__() as required, but the first parameter is always be the self argument. It is because, whenever a new instance of the class is created, the instance is automatically passed to the self argument in the .__init__() construct. So, as new attributes can be defined on the object.

class Person :
    def __init__(self, name, age):
        self.name = name
        self.age = age
Body segment of the definition

Note, that in the body segment of .__init__(), there are two self statements :

  1.  The self.name = name statement, which creates an attribute “name” which is then assigned to the value of the “name” argument.
  2. The self.age = age statement, which creates an attribute “age” which is then assigned to the value of the “age” argument.

Attributes which are created in .__init__(), are generally known as instance attributes. It is so because, an instance value is specific to a particular instance of that class. As in the name and age of object1 of the “Person” class.

On the other hand, there are another set of attributes, called the class attributes, These are attributes having the same value for all instances of that class.

Lets see an example :

class Person :
    species = "Home sapiens"    # Class attribute

    def __init__(self, name, age):
        self.name = name
        self.age = age

Now that we have a “Person” class, let’s look at creating objects for it. Or, in reality, lets create some Persons for the “Person” class.

Creating an Object

Creating an instance or more correctly object of the class is known as instantiating an object. To start with instantiation, lets delve into how to do so. Type the name of the class, followed by first bracket or parantheses :

Person()
<__main__.Person object at 0x208702d45>

One now has a new “Person” instance at the memory address 0x208702d45. Now lets create a new object :

Person()
<__main__.Person object at 0x00844ccd80>

We see that this new object is located at another memory address which is quite different from the memory address of the first object. That’s because it’s an entirely new instance and is also distinct in nature to the first object or instance of the class. Lets test it though for absolute clarification :

Shubham = Person()
Jeevan = Person()
Shubham  == Jeevan

Output : False

It is to note, that even though both Shubham and Jeevan are both instances of the same “Person” class, they represent entirely two unique objects in memory.

Object Class in Python — Miscellaneous Examples

# We will create a "ComplexNumber"class 
class ComplexNumber:
    def __init__(self, r = 0, i = 0) :
        self.real = r
        self.image = i

    def get_data(self) :
        print(f' {self.real} + {self.image}j')


# Now, creating a new object
com1 = ComplexNumber(3, 5)

# Now, lets call get_data() method

# Output: 3 + 5j
com1.get_data()

/*  Creating a Dog Class 

class Dog:
    species = "Canis familiaris"

    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Instance method
    def description(self):
        return f"{self.name} is {self.age} years old"

    # Another instance method
    def speak(self, sound):
        return f"{self.name} is saying {sound}"

tommy = Dog("Tommy", 5)

tommy.description()
'Tommy is 4 years old'

tommy.speak("Woof Woof")
'Tommy is saying Woof Woof'
/*  Creating a Square class

# class definition
class Square():
    def perimeter(self, side):
        return side * 4

# 1st object
sq1 = Square()
print("Perimeter of Object 1:", sq1.perimeter(50))

# 2nd object
sq2 = Square()
print("Perimeter of Object 2:", sq2.perimeter(5))

/*  Creating a greet method in the Person class
class Person:
    age = 10

    def greet(self):
        print('Hello')


# create a new object of Person class
Shubham = Person()

print(Person.greet)
/* Creating a Coffee Machine class
class CoffeeMachine:
    name = ""
    beans = 0
    water = 0
    
    def __init__(self, name, beans, water):
        self.name = name
        self.beans = beans
        self.water = water
        
    def addBean(self):
        self.beans = self.beans + 1
    
    def removeBean(self):
        self.beans = self.beans - 1
    
    def addWater(self):
        self.water = self.water + 1
    
    def removeWater(self):
        self.water = self.water - 1
    
    def printState(self):
        print "Name  = " + self.name
        print "Beans = " + str(self.beans)
        print "Water = " + str(self.water)

cocoa= CoffeeMachine("Cocoa", 203, 50)
pythonBean.printState()
print ""
pythonBean.addBean()
pythonBean.printState()

++ SUMMING UP — Object Class in Python

So, in this post, we got in-depth hold of objects and classes, the basic components of Object-Oriented Programming in Python. We learnt these concepts with the help of ample number of examples.

Thus, through this article, you shall have an idea about concepts of Object Class in Python. By and through this article, thus, I suppose I have made myself pretty clear. But, in case, you still have some doubts lingering. Then, please do write to me in the comments section and I am as always, ever-ready to help you. And, also solve your many queries and problems.

Until then bidding you Good-Bye !!! Ok, wait ….. before you go, you may check out my various other posts. Also, for the simple reason, that is, to enhance your knowledge on various other topics of importance. Also, where ??? Here…… And, if u still want more as in “Dil Mange More” then visit.