Explain Python classes and objects to my nephew (+advanced use)

Explain Python classes and objects to my nephew (+advanced use)Georgios DrakosBlockedUnblockFollowFollowingFeb 15It is common secret that Python programming language has a solid claim to being the fastest-growing major programming language witnessing an extraordinary growth in the last five years, as seen by Stack Overflow traffic.

Based on data describing the Stack Overflow question views which go to late 2011, the growth of Python relative to five other major programming languages is plotted.

What’s unique about Python?Python is an object-oriented programming language.

Object-oriented programming (OOP) focuses on creating reusable patterns of code.

When working on complex programs in particular, object-oriented programming lets you reuse code and write code that is more readable, which in turn makes it more maintainable.

Clever use of classes will ultimate benefit a Data Scientist at the stage of productionize its model.

Classes and ObjectsTwo of the most important concepts in object-oriented programming are:Class — A blueprint created by a programmer for an object.

This defines a set of attributes that will characterise any object that is instantiated from this class.

Object — An instance of a class.

This is the realised version of the class, where the class is manifested in the program.

These are used to create patterns (in the case of classes) and then make use of the patterns (in the case of objects).

Simply put Objects are an encapsulation of variables and functions into a single entity.

Objects get their variables and functions from classes.

Class is actually the pattern /blueprint for a new object that we can define later.

In the below example, the variable “myobjectx” holds an object of the class “MyClass” that contains the variables and the functions defined within the class called “MyClass”.

We manage to access the variable inside of the newly created object “myobjectx” by running the command myobjectx.

variable1 and myobjectx.


At the same time we can access the functions as they are under the class MyClassand are called methods.

Methods are a special kind of function that are defined within a class.

The argument to these functions is the word self, which is a reference to objects that are made based on this class.

To reference instances (or objects) of the class, self will always be the first parameter, but it need not be the only one.

One of the advantages is that we can create different objects that are of the same class(have the same variables and functions defined).

However, each object contains independent copies of the variables defined in the class.

Classes are objects tooAs soon as you use the keyword CLASS, Python executes it and creates an OBJECT.

In the below example when running the class command creates in memory an object with the name “ObjectCreator”.

It is still an object since:you can pass it as a function parameteryou can add attributes to ityou can assign it to a variableThe Constructor MethodBy adding the above __init__ method to the Shark class in the program above, the program would print automatically:"This is the constructor method.

"This is because the constructor method is automatically initialised (you will never have to call the __init__() method).

You should use this method to carry out any initialising you would like to do with your class objects.

For example:Difference between Class and Instances AttributesWhile instance attributes are specific to each object, class attributes are the same for all instances.

Attributes can be modifiedYou can change the value of attributes based on some behavior:Python Object InheritanceInheritance is the process by which one class takes on the attributes and methods of another.

Newly formed classes are called child classes, and the classes that child classes are derived from are called parent classes.

It’s important to note that child classes override or extend the functionality of parent classes.

In other words, child classes inherit all of the parent’s attributes and behaviours but can also specify different behaviour to follow.

It does make sense as jim and julie are instances of the Dog() class, while johnnywalker is not an instance of the Bulldog() class.

Then as a sanity check, we tested if julie is an instance of jim, which is impossible since jim is an instance of a class rather than a class itself—hence the reason for the TypeError.

Overriding the Functionality of a Parent ClassAs a class can override its class attribute in the same way a child class can also override attributes and behaviours from the parent class.

For example:The SomeBreed() class inherits the species from the parent class, while the SomeOtherBreed() class overrides the species, setting it to reptile.

Advanced: Why/How to use ABCMeta and @abstractmethodTo understand how this works and why we should use AGCMeta, let’s take a look at an example.

Let’s say we have a Base class “LinearModel” with two methods (prepare_data & fit) that must be implemented by all derived classes.

When we instantiate an object c and call any of it’s two methods, we’ll get an error (as expected) with the fit() method.

However, this still allows us to instantiate an object of the LinearModel() class without getting an error.

In fact we don’t get an error until we look for the fit().

This is avoided by using the Abstract Base Class (ABC) module.

Let’s see how this works with the same example:This time when we try to instantiate an object from the incomplete class, we immediately get a TypeError! Even if the fit function has been defined properly in the parent class.

This force us to complete the class LinearRegression to avoid any Errors:This time when you instantiate an object it works!Example when this can be usefulIf you make a GTA-like game where you can drive different vehicles, you create an abstract class “Vehicle” with an abstract method “drive”.

You then have different types of vehicles, each with its own class: “Car”, “Bike”, “Train”, … .

Each of these classes will have a different implementation of “drive”.

The train will be bound to tracks, the bike to lower speeds, the car to other rules, …This is much more efficient than having your drive method implemented in “Vehicle”.

You don’t need to add all the “if class == Car/Bike/…” bullshit, which is extremely ugly.

Also no vehicle will exist as just “Vehicle”, they will always belong to a child class, therefore the “Vehicle” class remains abstract, empty.

Stay tuned for my next article on Python metaclasses.

ConclusionObject-oriented programming is an important concept to understand because it makes code recycling more straightforward, as objects created for one program can be used in another.

Object-oriented programs also make for better program design since complex programs are difficult to write and require careful planning, and this in turn makes it less work to maintain the program over time.

Thanks for reading and I am looking forward to hear your questions :)Stay tuned and Happy Coding.


S If you want to learn more of the world of machine learning/coding you can also follow me on Instagram, email me directly or find me on linkedin.

I’d love to hear from you.








. More details

Leave a Reply