Hello! It’s Roberts Greibers here. 

Having worked in IT industry as a QA (software engineer) and later as a Python developer for more than 7 years, I’ve gathered numerous Python examples of classes.

I’ll tell you more about my experience as a Software Engineer/Python developer later in the post..  ⚡️

But now, let me list what Python classes examples you’re about learn in this post..

Read and pay ATTENTION!

You’re about to explore the MOST important parts of what is a class in Python! 🚀

One of the CORE understandings for objects in Python (Object Oriented Programming with Python)

In this post, you’re going to find out:

  • What is a class in Python?
  • How to define a Python class blueprint?
  • How to call Python class method?
  • How to execute Python class as a callable function?

I’ll do my best to make you understand classes in Python from this one blog post!

Also, if you’re coming from Javascript world, a keyword this might be familiar..

.. well in Python there isn’t “Python class this“, but there’s a similar concept we use.

And at the end, I’ll also share more about how my students are using classes in Python training – this might be an OPPORTUNITY FOR YOU to follow their steps!

More on that at the end of the post! 👇🏻

What Is A Class In Python?

When it comes to the question “What is a class in Python?” the easiest way to explain it is the following..

Objects in Python are defined as classes, you use class keyword to define a class which would be the “template” or the definition of how this particular object in Python is going to act.

Consider the following for classes in Python:

  • You can define your own Python class methods
  • You can define how class methods in Python will be executed
  • You can define what else will be done when you’ll call a class in Python (specific magic methods in Python help you with that)

I think you already get what I’m saying..

A Python class is a way of defining an object in Python. 

As a Python developer, you’ll work more and more with classes in Python as you’ll gather more experience, it’s just a natural progression for any developer. 

Any professional Python developer must be comfortable using Python classes, if that’s a new concept to you, consider reading the whole post, I’m gonna give you all the necessary information. 🔥

How To Find More Python Classes Examples

One of the best ways to learn what are classes in Python and how they’re supposed to be used in a real situation is by having a real project where you can simply use a search function and look up examples of class in Python. 

Even with all my experience, I’ve learned so much from our CTO and other senior Python developers in the company I’ve been working for the past 3 years. (You can find more details on my Linkedin)

Classes In Python - My work experience alongside senior Python developers at Spell 
for the past 3 years
Classes In Python – My work experience alongside senior Python developers at Spell
for the past 3 years

THE PROBLEM with such an approach is that most Python beginners won’t find a real project to look into!

Really well-developed projects aren’t just available online for everyone to look into!

And how would you know that the examples of class in Python you’re looking into are actually done correctly?

A large part of my daily work at Spell is the development of payment integrations, there’s no way to build a proper payment gateway backend without Python classes, everyone uses classes for Python backends. 👇🏻

“What is a class in Python?” – Why your co-workers can help you

But you have to be careful!

You can’t really rely on a random Python class example from online research if you’re not sure where it came from or what could be the pitfalls of using that particular example. 

This is WHY having experienced Python developers who can mentor you can be beneficial for YOU! 

One of the key benefits is that they can provide guidance and advice on how to effectively use Python classes. 

They can help you understand the concepts and principles behind Python classes, as well as how to apply them in real-world situations. 

Python Examples Of Classes For Students

For many Python beginners, my students included, Python class usage can seem HARD at first, they a bit of guidance to fully understand Python classes. 

After understanding classes in Python, everything starts to make sense.. 

When you first begin your Python journey you have no idea what is a class Python expects you to define..

One of my students after going through classes example in Python Mentoring
One of my students after going through classes example in Python Mentoring

What I usually tell my students is that they should consider that a Python class is a blueprint for creating objects.

And Python objects are instances of the class that contain their own unique attributes and behaviors. 

🚨 Mirabbos is a former student of mine, has achieved great results and is now looking for a full-time Python development job, similar to what Yuliia already achieved back in April 2022. 

If you are willing to work hard and have similar ambitions, find my contact information below this post or join my Discord server 🔥

I’ll see if there is a spot available for you, availability varies depending on the demand of students at a particular time of the year.

Python Example Of Class (Explained)

This Python class example is coming from one of the features I developed for the company I work for. Python class itself is a very small portion of the whole feature, but an important one. 

In short, I was working on a feature that involves an unknown amount of invoice delivery methods.

We started with email and text messages, but plan to add more delivery methods in the future.

A part of the feature is a REST API endpoint, this endpoint should validate user’s input and acceptable delivery methods. 

In Django REST framework for such purpose, we use serializers and serializers can have custom validator classes

The following code is a simplified version of a Python string validator class 

Before Python Example Class Definition

Before we get into defining a class in Python, let me define the following variables settings, InvoiceDeliveryMethodOptions and ValidationError

settings is a part of Django, but for the sake of simplicity, we’re going to use a simple class with a Python Dict in it. 

InvoiceDeliveryMethodOptions is an enum where in the future we’d add more delivery methods and build logic on top of them. 

import typing
import enum


class settings:
    FEATURES = {
        'invoice_text_message_max_length': 140
    }


class InvoiceDeliveryMethodOptions(enum.Enum):
    CUSTOM_MESSAGE = 'custom_message'

    @classmethod
    def choices(cls):
        return [(e.value, e.value) for e in cls]


class ValidationError(Exception):
    pass

ValidationError is a part of Django REST framework serializers, it’s a special exception type we use to raise exceptions from serializers, but for the sake of this example, I’m just going to use the default Python Exception.

How To Define And Call A Class In Python

Python class is a blueprint for creating objects. 

To define a class in Python, use the class keyword, followed by the name of the class. 

For example, here’s DeliveryMethodOptionsValidator with pass keyword.

class DeliveryMethodOptionsValidator:
    pass

validator = DeliveryMethodOptionsValidator()

print('validator: ', validator)

And just to see the result, you can create an instance in Python. 

An instance is an individual object of a certain class.

When you create an object from a class, the object is an instance of that class.

validator:  <__main__.DeliveryMethodOptionsValidator object at 0x1052c0130>

Besides having Python class properties, one of the most common Python class usage is having class methods.

Python class def lets you define functions that belong to the class, also called Python class methods.

class DeliveryMethodOptionsValidator:
    
    def validate_options(
        self,
        options: typing.Dict[str, str],
    ):
        print('options: ', options)
        breakpoint()


validator = DeliveryMethodOptionsValidator()

validator.validate_options(
    options={
        'custom_message': 'My text message'
    }
)

I needed to have a way of validating if provided delivery method options are known, otherwise raise an exception. 

So, before introducing any way of validating Python strings or Python Dict keys and values, let’s execute validate_options method and see if we can print options passed to the validate_options class method. 

options:  {'custom_message': 'My text message'}
--Return--
> /Users/robertsgreibers/projects/pythonic.me/python_class/1.py(39)validate_options()->None
-> breakpoint()
(Pdb)

Alright, now let’s find an elegant way of checking if there are any invalid options passed to the validate_options class method. 

For such purpose, let’s use a built-in function any()

class DeliveryMethodOptionsValidator:

    def validate_options(
        self,
        options: typing.Dict[str, str],
    ):
        has_invalid_option = any([
            (option, option) not in
            InvoiceDeliveryMethodOptions.choices()
            for option in options.keys()
        ])
        if has_invalid_option:
            raise ValidationError(
                f'{options} is not a valid json',
            )


validator = DeliveryMethodOptionsValidator()

validator.validate_options(
    options={
        'unknown_delivery_method': 'random value goes here'
    }
)

And just to test the functionality, let’s use an unknown_delivery_method.

This is the expected result – an exception was raised.

Traceback (most recent call last):
  File "/Users/robertsgreibers/projects/pythonic.me/10_python_class/1.py", line 70, in <module>
    validator.validate_options(
  File "/Users/robertsgreibers/projects/pythonic.me/10_python_class/1.py", line 63, in validate_options
    raise ValidationError(
__main__.ValidationError: {'unknown_delivery_method': 'random value goes here'} is not a valid json

In Django, this would turn into an HTTP response with a status code 400 and a payload containing:

{'unknown_delivery_method': 'random value goes here'} is not a valid json

Calling A Python Class Method vs __call__

Usually, you would be able to just use the above solution, define an instance of a class and call Python class methods.

That works in most Python class examples. 

But in this case, since I was implementing a validator class for a Django serializer, validator class had to be implemented with a magic method __call__

class DeliveryMethodOptionsValidator:

    def validate_options(
        self,
        options: typing.Dict[str, str],
    ):
        has_invalid_option = any([
            (option, option) not in
            InvoiceDeliveryMethodOptions.choices()
            for option in options.keys()
        ])
        if has_invalid_option:
            raise ValidationError(
                f'{options} is not a valid json',
            )

    def __call__(
        self,
        options: typing.Dict[str, str],
    ):
        self.validate_options(options)


validator = DeliveryMethodOptionsValidator()

validator(
    options={
        'unknown_delivery_method': 'random value goes here'
    }
)

I believe Django serializers can have both – functions and classes as validators passed to them, so it makes sense to turn a validator class into a callable function before passing it to the Django framework serializer..

Validate Python Strings With A Class Method

Finally, if we put everything togather to validate incoming text message string in Python this is what I came up with.

See validate_text_message_max_length() method. 

The idea is to use .get() method (available for any Python dictionary)

in a combination with a known enum InvoiceDeliveryMethodOptions.CUSTOM_MESSAGE.value to find if there’s a custom_message option passed to via serializer. 

Then, get a configurable invoice_text_message_max_length value from Django settings

And use it to validate the length of a custom message. 

If the length is too long, raise an exception. 

import typing
import enum


class settings:
    FEATURES = {
        'invoice_text_message_max_length': 140
    }


class InvoiceDeliveryMethodOptions(enum.Enum):
    CUSTOM_MESSAGE = 'custom_message'

    @classmethod
    def choices(cls):
        return [(e.value, e.value) for e in cls]


class ValidationError(Exception):
    pass


class DeliveryMethodOptionsValidator:

    def validate_options(
        self,
        options: typing.Dict[str, str],
    ):
        has_invalid_option = any([
            (option, option) not in
            InvoiceDeliveryMethodOptions.choices()
            for option in options.keys()
        ])
        if has_invalid_option:
            raise ValidationError(
                f'{options} is not a valid json',
            )

    def validate_text_message_max_length(
        self,
        options: typing.Dict[str, str],
    ):
        custom_message: typing.Optional[str] = options.get(
            InvoiceDeliveryMethodOptions.CUSTOM_MESSAGE.value
        )
        if custom_message is None:
            return

        max_length = settings.FEATURES['invoice_text_message_max_length']

        if len(custom_message) > max_length:
            raise ValidationError(
                f'Ensure "custom_message" key has no more than'
                f' {max_length} characters.',
            )

    def __call__(
        self,
        options: typing.Dict[str, str],
    ):
        self.validate_options(options)
        self.validate_text_message_max_length(options)


validator = DeliveryMethodOptionsValidator()

validator(
    options={
        'custom_message': '123'
    }
)

I hope this makes sense to you, if not comment below and I’ll see if I can help!

Bookmark this blog post page, use it as a template when you work with Python classes and I’ll guarantee you’ll be more productive.

Also, if you’re a part of any Python coding forums or groups on Facebook, Reddit, etc.

I’d appreciate it if you’d share this post! 📝

Why Do You Need Classes Example In Python?

On a surface level, it might seem like OOP with Python (Object Oriented Programming with Python) is EASIER compared to other programming languages..

Python kinda abstracts away a lot of the complexity of lower-level languages..

But, this also can make it more DIFFICULT..

… to understand how the code is actually being executed by your computer,

Especially if you’re learning by yourself, alone! 🤯

How To Master Object Orientation In Python

When it comes to working with object oriented programming in Python, there are specific syntaxes and rules you have to learn!

And this, of course, is NOT easy at all if you’re new to Python!

So don’t be too HARD on yourself! 🐍

Me (I used to be a QA engineer) and also my students, we all tried to find some guidance at the beginning of our journey into software development, it’s okay to ask for help!

Python Mentoring - A Discord server for students to ask questions regarding Python classes, etc.
Python Mentoring – A Discord server for students to ask questions regarding Python classes, etc.

It might NOT seem obvious to you, but books won’t fix your REAL problems..

Also, you can’t Google search away and magically become an experienced Python developer

Your REAL problem is that you DON’T have the exact steps in front of you to learn Python classes properly, become a Python developer and get a HIGH paying dev job!

You don’t have A SYSTEM, A PROCESS to follow..

It should be as simple as:

STEP 1, STEP 2, STEP 3, etc.. boom HIRED!

But on top of not having a system to follow, you’re trying to learn object oriented Python programming ALONE, without guidance..

How do you even know you’re on the RIGHT path?

Why You Should Throw Out All Python OOP Books

I understand this might sound crazy..

But the BIGGEST problem I see in people who have not yet mastered the following principles:

  • How to create a class in Python
  • How to create class methods in Python
  • How to Python call a class 

is the fact that they’re missing URGENCY in their lives..

They kinda want to become Python developers, but they’re kinda still fine with their current situation.

Become object oriented with Python - get metored by an experienced Python developer

When I had no money and no coding skills, I was willing to work 24/7 

I used to work 8h work days as a QA engineer, mix university lectures in between my working hours and do my homework during the evenings..

With all that I still managed to learn to code in Python at night!

Reading books is one of the SLOWEST ways to learn (just Google “learning diagram”)

You need to actually DO THINGS and have mentors to guide you!

I’m open to discussing your situation and even helping you if I’ll see potential in you becoming a Python developer!

⚠️ See if there are still details on how you can contact me below the post..

Classes For Python Mentoring Students

Understanding classes in Python DOES NOT require a lot of effort if you can just go through a couple of specific Python class examples and get your questions answered!

That’s exactly what I offer to my students, we’re having weekly Zoom Calls where everyone has the chance to ask their questions!

On top of that, I give students access to my own FRAMEWORKS, CHEAT SHEETS and exercises specially designed for one to understand Python concepts FAST! 🔥

🚨 I prefer to work with a small group of students as my time is VERY LIMITED please don’t message me if you’re NOT serious about becoming a Python developer! 🚨

This is a serious deal, If I work with anyone I invest my time and resources into your success!

As much as I’d like to help everyone..

I can’t help people who are NOT willing to work hard!

So, please make a serious decision – commit to this goal before you message me!

And if you’re in doubt, ask yourself –  WHAT DO YOU HAVE TO LOSE?

Talk soon!

I'll help you become a Python developer!

If you're interested in learning Python and getting a job as a Python developer, send me an email to roberts.greibers@gmail.com and I'll see if I can help you.

Roberts Greibers

Roberts Greibers

I help engineers to become backend Python/Django developers so they can increase their income