Learning Python: Classes

We are able to program using Object Oriented Programming (OOP) in Python. We can create classes, objects and methods.

Examples

A class is defined in the following way in Python:

class <name_of_class>:

Defining a class called Person:

class Person:
    # Person class

We define methods within a class like so:

class Person:
    def greeting(self):
        print('Hello!')

It is important to note here that self is equivalent to this in other languages, such as Java, C#, and JavaScript. It refers to the current instance of an object. self must be used when dealing with methods in a class.

We then can create an instance of the above class as follows:

new_person = Person()

If we wanted to output the type of new_person, we would get the following output:

print(type(new_person)) # <class '__main__.Person'>

In order to define a constructor which is used to initialize an object of a class, we use __init__():

class Person:
    def __init__(self, name):
        self.name = name
    
    def greeting(self):
        return 'Hello!'

new_person = Person('Peter')

print(new_person.name) # Peter
print(new_person.greeting()) # Hello!

We can also implement inheritance. Inheritance is one of the principles of OOP. It can be used in the following manner in Python:

class Person:
    def greeting(self):
        print('Hello!')

class Student(Person):
    def identify(self):
        print('I am a student')

new_student = Student()
new_student.greeting() # Hello!
new_student.identify() # I am a student

This blog post was originally published on my blog Communicode, where I write about different tech topics.

Python
Avatar for Muhammad Asfour

Written by Muhammad Asfour

I am a Full Stack Developer with over 5 years of experience. I have worked with different tech stacks such as: Groovy/Java, PHP, .NET/.NET Core (C#), Node.js, React, Angular, and Vue.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.