Python programming language is inherently Object Oriented Programming(OOP) language. Here we show different ways of writing simple python class and how to create object of the class. Progressively we show how to use the __init__ special method in a class and why they are used or needed.

We do this using progressive examples as follows.

First Python Class and object example

The simple class below has an attribute called name and a method called printer. In the argument of class ExampleA we pass into object as parameter. This is not required in new version of python.


class ExampleA(object):
    name = "This is name attribute of ExampleA class"
    def printer(self):
        print("This is printer method of ExampleA class")

This class is defined in the module called mymodule.py. Now we create an instance of the class ExampleA called simple a. And then use the a object to access the attribute name and method printer.

We can test the class using console or using python program. Here we create a python program called program.py whose content is as follows.

from mymodule import ExampleA

a = ExampleA()

print(a.name)
print(a.printer())



And if we run this program.py then we get the following output in the console.

This is name attribute of ExampleA class
This is printer method of ExampleA class

The first line is due to print(a.name) and the second line is due to print(a.printer())

Second Python Class and object example

The second example is similar to the first example. But here we don't specify the object parameter to the class. That is we drop object in ExampleA(object) and instead of ExampleA we have ExampleB. Everything else is the same.

class ExampleB:
    name = "This is name attribute of ExampleB class"
    def printer(self):
        print("This is printer method of ExampleB class")


As before we write the a python program. To ease we change the same program program.py. The program.py for this example is as follows:

from mymodule import ExampleB

b = ExampleB()

print(b.name)
print(b.printer())

The output is as follows which is the same as for the ExampleA class:

This is name attribute of ExampleB class
This is printer method of ExampleB class


Third Python Class and object example

In this example, we will use the object class parameter and the __init__ method. The __init__ method is a special method for python class whose application is to initialize the class attributes to some value aka to a known state.

class ExampleC(object):

    def __init__(self):
        self.name = "This is name attribute of ExampleC class"
    def printer(self):
        print("This is printer method of ExampleC class")


As for all python methods the self parameter is madatory to identify each class instances/objects from one another. As you can see we placed the name attribute inside the __init__ method instead of floating it outside any methods. The way of writing the name attribute in case of ExampleA and ExampleB classes is called static attribute.

The following is the program.py for this ExampleC class.

from mymodule import ExampleC

c = ExampleC()

print(c.name)
print(c.printer())

The output is as follows:

This is name attribute of ExampleC class
This is printer method of ExampleC class

Fourth Python Class and object example

The fourth example drops the object class parameter and everything else is the same as ExampleC class. The reason for showing this is just to show that the object parameter can be dropped and we get the same result, that is to ensure you on any doubts.

class ExampleD:

    def __init__(self):
        self.name = "This is name attribute of ExampleD class"
    def printer(self):
        print("This is printer method of ExampleD class")


The program.py for this example is as follows:

from mymodule import ExampleD

d = ExampleD()

print(d.name)
print(d.printer())

And when we run this program we get the following output:

This is name attribute of ExampleD class
This is printer method of ExampleD class

Fifth Python Class and object example

Upto now we have not been doing anything then writing the simplest form of python class and creating object and accessing its attributes and methods.

Now, what we will do is to create a class ExampleC which has __init__ method that accepts some attribute parameter called x. Look at the following example.

class ExampleE:

    def __init__(self, x):
        self.name = "This is name attribute of ExampleE class"
    def printer(self):
        print("This is printer method of ExampleE class")


As you can see the __init__ method we now have an argument parameter called x. What is it doing there and what is its purpose. Do we need this?

Let's create a program which is same as before, that is creates and objects and accesses the attribute name and printer method.

from mymodule import ExampleE

e = ExampleE()

print(e.name)
print(e.printer())


As you can see this is the same program as other example above. Running this code however produces error-

Traceback (most recent call last):
  File "D:/program.py", line 4, in <module>
    e = ExampleE()
TypeError: __init__() missing 1 required positional argument: 'x'

The error is TypeError and it is saying that the __init__() method is missing the argument x.

That is to use the __init__ method we must pass in the required argument parameter x. But how to pass the parameter x into __init__ method while running the program? That is where in the following program do we provide the necessary input-

from mymodule import ExampleE

e = ExampleE()

print(e.name)
print(e.printer())

We have to do the following-

from mymodule import ExampleE

e = ExampleE("John")

print(e.name)
print(e.printer())

We pass the value of x as John in the instance/object creation e = ExampleE("John"). Now if we run we won't get any error and the output will be as follows.

This is name attribute of ExampleE class
This is printer method of ExampleE class

But you are asking now what is the use of the parameter x or its value John? It has never been useful. To understand this we go to next example.

Sixth Python Class and object example

To understand the usefulness of using x in the __init__ method, let's try to use x in the class code. x = John which is a name. We can try to print out the name in the printer method. But how, let's look at one try-

class ExampleF:

    def __init__(self, x):
        self.name = "This is name attribute of ExampleF class"
    def printer(self):
        print("This is x: ", self.name)

As you should expect this is not what we intended but for sake of showing what it does. Let run the following program.

from mymodule import ExampleF

f = ExampleF("John")

print(f.name)
print(f.printer())

The output is:

This is name attribute of ExampleF class
This is x:  This is name attribute of ExampleF class

As you can see the output is not the value of x but the attribute name which is a string "This is name attribute of ExampleF class".

So in order to access the user input value for x we must assign the name attribute to parameter x. This is shown below.

class ExampleF:

    def __init__(self, x):
        self.name = x

    def printer(self):
        print("This is x: ", self.name

The program is the same:

from mymodule import ExampleF

f = ExampleF("John")

print(f.name)
print(f.printer())

And we get the following output:

John
This is x:  John

What is the point?

The point is that we have initialized the name attribute to a value John through x,

def __init__(self, x):
    self.name = x

when we created an instance/object of the class,

f = ExampleF("John")

Effectively, self.name = John via the x parameter of __init__ method.

Thus we have initialized an attribute name of a class. And when we create an instance, the attributes have initial state or values such as John in this case.

This way of initializing attributes in Python is similar to the constructor in C++ programming language.

 

0 comments:

Post a Comment

 
Top