How to create a class in python ?

Published: March 26, 2021

Tags: Python;

DMCA.com Protection Status

Quick tutorial on how to create and use classes in python:

Create a simple class in python

To create a simple class called for example member, with a single property named s, just do

class member: 
        s = 'Hello world !'

Then to create an object from this class (or an instance of the class member):

member_01 = member()

and to get the property named s:

member_01.s

returns here

Hello world !

Note: to create a class with no property, a solution it to use "pass"

class member: 
        pass

Use the init() function to assign values

So far, our class is not really useful. The next step is to provide some variables to initialize our objects. To do that create an init() function, for example:

class member:

        def __init__(self, first_name, last_name, age):
                self.first_name = first_name
                self.last_name = last_name
                self.age = age

Now to construct our object we have to provide 3 variables:

member_01 = member("John", "Doe", 24)

print(member_01.first_name)
print(member_01.last_name)
print(member_01.age)

returns

John
Doe
24

We can then create different objects from the class member, for example

member_02 = member("Emma", "Watson", 30)

print(member_02.first_name)
print(member_02.last_name)
print(member_02.age)

returns

Emma
Watson
30

Add optional parameter in class initialization using *args

With the following class

class member:

        def __init__(self, first_name, last_name, age):
                self.first_name = first_name
                self.last_name = last_name
                self.age = age

if you add an optional variable for example the gender ('Male. here)'

member_01 = member("John", "Doe", 24, 'Male')

you will get the following error message:

TypeError: __init__() takes 4 positional arguments but 5 were given

To pass some additional variables a solution is to use *args:

class member:

        def __init__(self, first_name, last_name, age, *args):
                self.first_name = first_name
                self.last_name = last_name
                self.age = age

then the following line will not returns any error message.

member_01 = member("John", "Doe", 24, 'Male')

Now to do something with the optional variable:

class member:

        def __init__(self, first_name, last_name, age, *args):
                self.first_name = first_name
                self.last_name = last_name
                self.age = age

                if 'Male' in args:
                        self.gender = 'male'

then

member_01 = member("John", "Doe", 24, 'Male', 'White')

print(member_01.gender)

returns

male

Add optional parameter in class initialization using **kwargs

Another solution is to use **kwargs, example

class member:

        def __init__(self, first_name, last_name, age, **kwargs):
                self.first_name = first_name
                self.last_name = last_name
                self.age = age

                if 'height' in kwargs:
                        self.height = kwargs['height']

member_01 = member("John", "Doe", 24, height=5.3, eye_color='green')

print(member_01.height)

returns:

5.3

Add Object Methods

It is also possible to define object's method (i.e. function defined inside a class). For example let's define a function that returns the full name:

class member:

        def __init__(self, first_name, last_name, age):
                self.first_name = first_name
                self.last_name = last_name
                self.age = age

        def full_name(self):
                return "Full name: {} {}".format(self.first_name,self.last_name)

then

member_01 = member("John", "Doe", 24)

print(member_01.full_name())

will returns

Full name: John Doe

Delete an object

To delete an object just do:

del member_01

Create child class (Inheritance)

Another important feature of class is called class Inheritance. For example, let's re-use our previous class:

class member:

        def __init__(self, first_name, last_name, age):
                self.first_name = first_name
                self.last_name = last_name
                self.age = age

        def full_name(self):
                return "Full name: {} {}".format(self.first_name,self.last_name)

We can define a sub class called for example "premium_member" (a child class) from the class member (parent class):

class premium_member(member):
        pass

Then, we can create an new object from premium_member

pm1 = premium_member("John", "Doe", 24)

and

print( pm1.first_name )

returns

John

Note that here the class premium_member inherit everything from the class member. Even object's method defined in class member:

print( pm1.full_name() )

returns

Full name: John Doe

Now if you try to add an init function inside the class premium_member:

class premium_member(member):

        def __init__(self, first_name, last_name, age):
                pass

then

pm1 = premium_member("John", "Doe", 24)

print( pm1.first_name )

will returns the error message:

AttributeError: 'premium_member' object has no attribute 'first_name'

because the child's init() function overrides the inheritance of the parent's init() function.

To avoid that a solution is to add member.init(self, first_name, last_name, age):

class premium_member(member):

        def __init__(self, first_name, last_name, age):
                member.__init__(self, first_name, last_name, age)

then

pm1 = premium_member("John", "Doe", 24)

print( pm1.first_name )

returns

John

or another solution is to use super():

class premium_member(member):

        def __init__(self, first_name, last_name, age):
                super().__init__(first_name, last_name, age)

Inside a child class you can then define additional methods, for example:

class premium_member(member):

        def __init__(self, first_name, last_name, age):
                super().__init__(first_name, last_name, age)

        def promo_code(self):
                return 1234

then

pm1 = premium_member("John", "Doe", 24)

print( pm1.promo_code() )

will returns

1234

References