DEV Community

akshat-2110
akshat-2110

Posted on

Peeling the Backend of the Classes

Any programming language and Python especially there's a lot of high-level syntax and great features that you can use without having any understanding of how they actually work on the backend.

Alt Text

So if we notice that, We were able to add 25 in x as both were int type instance of the class. These classes are like blueprints that define the behaviour of different objects in Python.

Alt Text

We get an error it says unsupported operand types for int and string so since one of these variables is type string and the other is type int We cannot add them together because that operation is not defined and so just keep that in mind there that these classes or these types really are blueprints defining how objects can behave in our program what methods we can use on them what operations or operators we can use with them it's a blueprint defining the behaviour that's really the key thing.

Let's now create a Student class
Alt Text

If we notice there is some strange behaviour in the two outputs above. The type of instance of the class object x is class 'main.Student' and the type of instance of actual class Student is class 'type'.

When we think of creating a class we think of creating a new type
right we're creating this Student class 'type' and we can create objects of type Student but it turns out the classes themselves are objects that are of the class 'type'.

This is because we actually have a blueprint above our object or
above our class that defines how we can create a class.

Now let see how we can create this exact same class without using this high level fancy syntax
Alt Text

This is how you can actually create a class using this type function and this is because again there is a blueprint above our kind of pre-built in classes here that tells you how to define a class. Now we can do very advanced thing like dynamically creating a class.

We can write the classes in two different way one is the fancy way as we do normally and the other is going down to the bare-bones level and create the class on your own.
Alt Text

This will most useful while defining meta-classes.
As we already know now that Student class is of that means we can create a class that actually is a subclass of class type and use that class to create new classes

Alt Text

Now if we see it works exactly the same because what we have done is we have created the blueprint for the class i.e., CreateClass.
Now we have full flexibility to change the behaviour of Class like: How a class is constructed, What methods are called first(init method should called first or not), etc.

Top comments (0)