28. Class#

As Python 🐍 is a Object Oriented Programming Language, we get the fruits like Inheritance, Encapsulation, Polymorphism and Data Abstraction. If you are already familiar with other OOP languages like C++, Java you might have already heard of these scaring jargons, if not, don’t worry, let’s get to know about them in simple funny terms.

28.1. What the heck is class 🤔?#

A class is a blueprint which describes the data and various methods which help to manipulate or use the data specific to it.

A class is created using the Keyword class.

Let’s start by creating a simplest possible class 😎

class IAmASimpleClass:
    pass

Yipee! We did it 😬. Let’s confirm it 👇

import inspect

print(f"IAmASimpleClass is class: {inspect.isclass(IAmASimpleClass)}")
IAmASimpleClass is class: True

Hint

isclass function of inspect module is used to check whether the object/argument is class or not, If class, returns True, else False.

As in our IAmASimpleClass we haven’t written any code inside it, we might think there is neither data nor methods associated with it, but that’s not the case. There are methods associated with our class 🔍. let’s check it.

We will be using dir function to get to know all the attributes associated with our class

dir(IAmASimpleClass)
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getstate__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__']

Yup, we see few things are present. But from where did we get those? I am sure, there’s no magic here. It’s time to be a detective 🕵

We all must have already heard or read that In Python everything is an Object. Well, the culprit in the above example is the class object ⚔️. All the above attributes or methods in the output are inherited from the class object. In Python3, by default every class inherits object class.

class IAmASimpleClass:  # Python3 takes care of inheriting object.
    pass


class IAmASimpleClass(
    object
):  # We can explicitly inherit object, although not required.
    pass

Both the above classes are pretty much equal. Feel free to use any of those, If you are as lazy as me, I would recommend you to use the first method(New-Style classes) and let Python take care of inheriting object for us.

Note

Second method of inheriting object is generally used if we want to use code which is agnostic to both Python3 and Python2. But let’s not get confused with Python2 way of creating classes “classic-way” and “new-style” as Python2 already passed EOL and dead.

Yup, we got our answer, All the attributes or methods which we saw in our output are from the class object. 😊

As we have reached our first milestone of creating a simple class, let’s get to know a bit more about class.

class SuperHero:
    def __init__(
        self, name, power_level, special_power
    ):  # One of the special/magic/dunder method.
        self.name = name  # Instance attributes.
        self.power_level = power_level
        self.special_power = special_power

    def introduce(self):  # Method.
        return f"Hey! I am {self.name}, my special power is {self.special_power} and have a crazy power level of {self.power_level} 🔥"

Let’s go bit by bit about our SuperHero class.

As we said class is a blueprint which describes the data and various methods which help to manipulate or use the data specific to it. let’s point out what are the data and methods here.

28.1.1. __init__#

The first line inside our class SuperHero, we see a function(actually a method) called __init__. This is one of the special/magic/dunder methods present in Python classes. Whenever we try to create a new instance of class, __init__ method gets called.

But, what is the role of parameters in the __init__ signature as?

def __init__(self, name, power_level, special_power):

While creating objects for our class, we pass the parameters as:

super_hero = SuperHero("Iron Man", 1000000, "Jarvis")

Note

🤔 we see that, in __init__ method, we have 4 parameters self, name, power_level, special_power, but during initialization of the object, we just passed 3 arguments, and it worked without raising any exceptions 😳. The reason is the __new__ method of object(universal base class) is called before __init__ implicitly which actually creates the object and passes the object for self argument. No hurry, we would see it in action soon 😊.

What exactly is self? The self argument in the methods is the representation of the instance or object created out of that class.

Note

The word self is just a convention among the Python community, there’s no hard rule here, we can replace self with any word, just that it shouldn’t be a Python Keyword 😬.

28.1.2. Instance attributes#

We see few assignments in the __init__ method as:

self.name = name  # Instance attributes.
self.power_level = power_level
self.special_power = special_power

As we learnt that self represents the object created out of the class, we are assigning the arguments name, power_level, special_power to self.name, self.power_level, self.special_power respectively. In this way, we create attributes which belong to the object.

Tip

Instance attributes can be named any, we don’t need to always name instance attributes same as arguments names.

That’s great 🎊! We learnt about how to create an instance of class and instance attributes.

28.1.3. Methods#

Methods are basically functions that are bound to classes and interact with class or instance attributes 😬. In simple words methods are just functions but are members of a class.

In our SuperHero class, we have a method called introduce. let’s call it 🔛.

super_hero.introduce()
'Hey! I am Iron Man, my special power is Jarvis and have a crazy power level of 1000000 🔥'

Well, our introduce method introduced Iron man very well, But we already knew our beloved Super Hero Iron man in first place ❤️

Iron man says hello

Hint

class vs class object through an example:

class is a blueprint of the House 📜.

class object is the actual House 🏠.