Pythonize : Classes in Python

This series of articles, “Pythonize” will serve as an aid for python beginners. In this chapter I will try to explain all about python classes. In this series I will let python code talk to you more than me.

A few interesting things about python for you: Internet giants, Google and Yahoo, maintain a large code-base in python and promotes python to a large extent. Google apps can now be developed in python using the python APIs provided by Google. Python is famous for more functionality in less time being a scripting language and at the same time enabling OOP(Object Oriented Programming). It’s rich with libraries and online help. You can access

 

Python Class:

Class is a template or prototype that defines the fields and methods common to all objects created with this class. Classes in python starts with the keyword ‘class’ followed by the class name and then an optional set of classes separated with comma inside parenthesis, which will be inherited into your class depth-first and left-to-right order. It is then ended with a full-colon and all the indented block of statements just after that forms the body of the class. Note: Python keywords are case-sensitive. Stick with small letters. Below code won’t compile.

E.g.

Image FYI: pass is the keyword used to avoid error and it represents an empty block here. Variables: Data type of python variables is set based on the value assigned to it. Some valid variable assigning:
E.g.

Image

Hope you noted that I have reassigned ‘variable1’ from number to string without any extra code and the program worked fine. That is the extent of freedom python gives you. There is no keyword to define the scope of variables in class and all your usual variables declared inside class will be publicly accessible. Let try this with an example.

E.g.

6a Output: 6 Recent python versions came up with a solution to declare private variables. You just need to precede your variables with two underscores (__) and magic: it became private. Such private attributes are declared outside __init__ function for data hiding. Lets experiment this with a few lines of code.

E.g.

7a Output:

7

You may doubt that this is because I tried to print the variable ‘name’ where the class variable is “__name”. Lets clear your doubt.

E.g.

8a Output: 8

Here we tried to print the same variable name. Since preceding class-variables with two underscores make it private, we got an ‘AttributeError’. Python protects such private members internally by altering its name to contain the class name and we can access such members by following the template:

<objectName>._<className>__<attributeName>

Here our object name is prs, class name is Person and the variable is __name, so as per our assumption we should get the variable value by printing ‘prs._Person__name’

E.g.

8-1a Output: Note: Use “self.” with variable names to refer to instance variables and class-name followed by period (.) and then variable name to refer to class variables. Otherwise python will consider it as a global name and raise an error or give unpredictable outputs if a global variable with similar name exists. Lets have one example of class variables and then go to next topic:

E.g.

Image Output: 10 Here, you can see that by changing company name of emp2, it got reflected in emp1 as well i.e. emp1 and emp2 points to a single memory and such variables are technically called as class variables; one single memory for all the classes.

 

Class functions:

Functions of class decide the behavior of the class. They act as an interface to the outside world. Take a look at a sample class with a function ‘print_emp_details’.

E.g.

9a

Output: 4

Constructor:

Object Oriented Programmers might already know the role of constructor in a class. For those who don’t, let me explain. Constructor is the function that gets automatically invoked at the time of object-creation which is usually made use of for resource allocation. Python differs a bit from other OOP languages like java or C++ in constructor-name and it’s invocation. In python,

  • constructor of parent classes will not get invoked at the class of object creation of child class.
  • constructor function in python is always __init__().

E.g.

Image

You might be wondering about ‘self’ in __init__ function. In python, you will see this variable as the first argument in all the class functions without which the execution will fail. ‘self’ is not a keyword but instance of a class. You can use any other name for this parameter but it’s part of coding standard, which makes your code readable and easy to understand for other programmers. Lets stick to that standard.

E.g.

Image

Output: 1

A blank parameter list will raise a TypeError:

E.g. Image Output:

3

We have seen only constructors that don’t take any parameters so far. Now lets take a peek into parameterized constructors. As you guessed, the parameters of the constructor follow ‘self’.

E.g. 4a

Here name and hobby are the arguments and during object-creation we passed the arguments string “Sreejith” and “programming” as name and hobby to the constructor. One thing to note is that, with this class you won’t be able to create an object without any parameters. You will get the following error:

E.g.

4b

Output:

4c

Lets see a work around for that. Here we will assign a default value for the constructor variables and thereby the constructor assumes the default value if not explicitly specified at the time of object creation.

E.g.

4d Output: 4e

 

Destructor:

E.g.

11

Output: 11

 

Other base methods you can overload in your class:

  • __repr__(self)
    • To represent the object in evaluatable string
    • E.g.: repr(obj)
  • __str__(self)
    • To represent the object in string
    • E.g.: str(obj)
  • __cmp__(self, obj1)
    • For comparing with another object
    • E.g.: cmp(obj, obj1)

Inheritance:

Lets straight away get into a python code that successfully uses inheritance to reuse code and at the same time overrides needed functions.

E.g.

Image Output: 12 Here we override the print_name() function in Child and GrandChild class but uses the same smile() function as such. Functions are searched in the following hierarchy:

  1. Derived class
  2. Base class in the order of depth first and then left-to-right.

There are two functions which comes handy with class inheritance:

  • issubclass()
    • Returns a boolean value based on if the first parameter is a sub-class of the second parameter.
    • E.g.: issubclass( subclass1, superclass1 )
  • isinstance
    • Returns a boolean value based on if the first parameter is an object of second parameter.
    • E.g.: isinstance( object1, class1 )

Thus we have come to the end of this chapter. Lets recall what we have learned from this chapter. We learned

  1. Basic syntax of class
  2. Variables; How to make variables private; Class variables and Instance variables
  3. Class Functions/Methods
  4. Inheritance; Function overriding

Meet you next time..

Published by

Sreejith

A strong believer of: 1. Knowledge is power 2. Progress comes from proper application of knowledge 3. Reverent attains wisdom 4. For one's own salvation, and for the welfare of the world

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s