Python Data Persistence – class Keyword

Python Data Persistence – class Keyword

Apart from various built-in classes, the user can define a new class with customized attributes and methods. Just as a built-in class, each user-defined class is also a subclass of the Object class. The keyword ‘class’ starts the definition of a new class.

Example

>>> #user defined class
. . .
>>> class MyClass:
. . . pass
. . .
>>> type(MyClass)
<class 'type'>
>>> MyClass.__bases__
(<class 'object'>,)
>>> issubclass(MyClass, object)
True

A user-defined name is mentioned just beside the class keyword and is followed by a symbol to initiate an indented block containing its attributes and methods. In this case, the class body contains just one statement pass which is a no-operation keyword.
Above code clearly indicates that the user-defined class is subclassed from the object class. It means that any Python class, built-in or user-defined is either directly or indirectly inherited from the parent object class. To underline this relationship explicitly, the MyClass can very well be defined as follows:

Example

>>> class MyClass(object):
. . . pass
. . .
>>> MyClass.__bases__
(<class 'object'>,)

Now we can have objects of this class. The library function dict() returns an empty dictionary object. Similarly, MyClass( ) would return an empty object because our new class doesn’t have any attributes defined in it.

Example

>>> obj1=MyClass( )
>>> obj2=MyClass( )

It is veiy easy to add attributes to this newly declared object. To add ‘myname’ attribute to obj 1, give the following statement:

>>> obj1.myname='Ashok'

There is also a built-in setattr ( ) function for this purpose.

>>> setattr(obj1, 'myage',21)

The second argument for this function may be an existing attribute or a new one. The third argument is the value to be assigned. You can even assign a function to an attribute as shown below:

Example

>>> def about me(obj):
. . . print ( ' My name is { } and I am { } years old ' . format ( obj,myname,obj.myage ) )
. . .
>>> setattr(MyClass, 'about', aboutme)
>>> obj1.about( )
My name is Ashok and I am 21 years old

So you have been able to add new attributes to an individual instance or class. Even from outside the class! If you have honed your object-oriented programming skills by learning Java or C++, this might send shivers down your spine! On the face of it, this seems to be a violation of the very idea of class which is a template definition of an object’s attributes. Don’t worry; we will soon make a Python class work as per OOP guidelines.