The concept of Objects and Classes together comes under the aegis of OOP or Object- Oriented Programming. OOP is therefore, a method to structure a set of instructions 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 post, therefore, we take on the topic Class definition in Python.

Object Oriented Programming

The concept of Object-oriented programming or OOP basically focuses on building re-usable styles of code and hence more easily readable and maintanable. A marked contrast to the other concept of procedural programming, which explicitly focuses on the sequential execution of instructions.

There are basically two very important terms or so as to say components/integrants in the Object-Oriented Programming concept. These are Class and Object, which are being defined below :

  • Class — A class is nothing but a blueprint created for an object. It basically defines the set of attributes which will be use to characterize any object instantiated from that class. Thus, it is a pre-defined, set template for an object.
  • Object — An object is nothing but an instance of a class. The class attributes gets manifested in the object. In layman terms, an object inherits the attributes or characteristics of the class it is instantiated or realized from.

Thus, we can also say that classes are like patterns which get utilized in objects.

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.

Class definition in Python

Definition of Class in Python

A definition of the class starts with keyword of the same name, “class” which is follows 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 indicates 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.

Class definition in Python

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 assign to the value of the “name” argument.
  2. The self.age = age statement, which creates an attribute “age” which is then assign to the value of the “age” argument.

Attributes which are create through .__init__(), come to be 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 is another set of attributes, 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()

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

Person()

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.

Class definition 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 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 — Class defintion in Python

So, in this post, we got in-depth hold of objects and classes, the basic components of Object-Oriented Programming in Python. Also, we saw the different methods to create classes. We saw about class definition in Python. We learnt these concepts with the help of ample number of examples.

Thus, through this article, you shall have an idea about concept of Class and Objects 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.

Categorized in: