How to write your first class in Python

Many beginners on the path of learning the Python computer programming language face a lot of struggle when they deal with intermediate concepts and utilities such as functions and classes. Having experienced a lot of struggle myself with class objects in the beginning of my journey as a coder, I decided to share some knowledge with the main purpose of easing the learning process of those passionate beginners who are completely new to some of the most important concepts in object oriented programming.

First of all, let me explain why the class object is truly important to the coder. Based on my experience with the Python computer technology, the class object is mostly used to group functionalities together and also speed up the process of software development.

As far as my wisdom goes about the class object in the Python computer programming language, the coder can easily make use of it to write base classes and later inherit from them with the main purpose of customizing.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

Before going any further with this article, make sure to launch a new interactive shell in your own operating system so you can practice the knowledge being shared in here.

Once you have managed to launch a new Python console on your own machine, you can easily declare a fresh class object by making use of the following syntax.

class A(object):
    pass

As you have probably guessed, the above class does nothing, it does not define any data or utility. How can one make use of the above class?

The classes in the Python computer programming language, serve as a fabric for generating instances, which are the real objects. The Python coder can easily generate an instance from their class by making use of the syntax being shown in the following example.

a = A()  

One can also use the builtin print statement by passing their instance as an argument to it. The following example is an illustration.

print(a)

Once I executed the above piece of Python code on my interactive console, I got the following output.

<__main__.A object at 0x0000000001D2CB38>

As you can see from the above output, our instance is an object in Python. Since classes in the Python programming language, or any other object oriented computer language usually have attributes, one can easily access their attributes directly from the instance by using the following syntax.

instance_object.attribute

For example, to access an attribute part of the instance declared above, the following syntax can be used.

a.name

Once the above piece of Python code got executed on my interactive console, I got the following error.

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    a.name
AttributeError: 'A' object has no attribute 'name'

The above traceback informs the user that the ‘A’ object has not an attribute ‘name’. Each time the coder tries to access an attribute which is not present in their object, an error will be thrown.

The Python coder can easily define attributes in their classes by making use of the syntax which is shown below.

class Student(object):
    def display_lastname(self):
        pass

    def display_name(self):
        pass

The above class called Student, defines two attributes: display_lastname and display_name. For now, they don’t do anything, but it is possible to access them by making use of the syntax which is being shown below.

s = Student()
s.display_lastname()
s.display_name()

Now that you have learned how to access attributes of an instance object which is generated from a class, it is time to write the full code for the ones that we defined above.

class Student(object):
    def display_lastname(self):
        print(self.name)

    def display_name(self):
        print(self.lastname)

Where do self.name and self.lastname come from? They’re instance attributes. Usually a class in the Python computer programming language has a constructor, which takes initial arguments and is the first method which gets automatically executed once an instance is being created from it.

The syntax for the constructor of the class is being shown below.

__init__(self, *args)

To make the class Student fully functional, we need to add a constructor to it. The following syntax can be used to add the constructor to our class.

class Student(object):
    def __init__(self, name, lastname):
        self.name = name
        self.lastname = lastname
  
    def display_lastname(self):
        print(self.name)

    def display_name(self):
        print(self.lastname)

As you can see from the above piece of Python code, the constructor of our class Student takes two initial arguments; name and lastname. Both of them are required by default in the initialization of every instance object which the coder generates from the class Student.

What about the argument self? It is decided by Python developers that the first argument of every class constructor should be self, it is replaced by the instance object.

Let’s create a fresh instance object by making use of the above class. The code for it is being shown below.

s = Student('oltjano', 'terpollari')

The above piece of Python code creates an instance object called s. As you can see, the argument name is given a value, the same for the argument lastname.

Based on my experience with the Python computer programming language, self.name and self.lastname are attributes which belong to the instance s.

We can easily access them by using the following syntax.

s.name
s.lastname

Once I executed the above Python commands on my interactive console, the following output was displayed.

'oltjano'
'terpollari'

The Python coder can easily access the other attributes of his or her instance object. Each one of the functions defined in the class Student, is known as a method.

For example, to execute the method display_name of instance object s, the Python coder makes use of the syntax which is shown in the following example.

s.display_name()

The same syntax should be followed for the other method, called display_lastname.

s.display_lastname()

Final thoughts

The class object in the Python computer programming language is a concept which deserves a lot of research and attention. It is not possible to cover it in details in a single article.

Through this tutorial you learned how to write your first class object and also make use of it in an instance object. As you saw from the practical examples being shared in here, the Python class object is a great tool to group and package functionalities together. Codetheory.in will provide many articles in which the class utility will be used in real world scenarios.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

Leave a Reply

Your email address will not be published. Required fields are marked *