Python Data Persistence – Constructor

Python Data Persistence – Constructor

We provide a constructor method to our class to initialize its object. The__init__( ) method defined inside the class works as a constructor. It makes a reference to the object as the first positional argument in the form of a special variable called ‘self’. Java/C++ programmers will immediately relate this to ‘this’ variable. A method with ‘self argument is known as an instance method. Save the following script as myclass.py. It provides two instance variables (my name and my age) and about () method.

Example

#myclass.py ‘
class MyClass:
            def __init__(self):
self.myname='Ashok'
self.myage=21
def about(self):
print ('My name is { } and I am { } years old'.format(self.myname,self.myage))

Let us use this script as a module, import MyClass from it and have its object.

Example

>>> from myclass import MyClass
>>> obj1=MyClass( )
> > > obj1.myname
'Ashok'
>>> obj1.myage
21
>>> obj1.about()
My name is Ashok and I am 21 years old

So, now each object will have the same attributes and methods as defined in the class. However, attributes of each object will be initialized with the same values as assigned in__init__( ) method. To counter this, we can have a parameterized constructor, optionally with default values. Modify Now we can have objects having attributes with different values.

Example

>>> from myclass import MyClass
>>> obj1=MyClass('Ashok', 21)
>>> obj2=MyClass('Asmita',20)
>>> obj1.about()
My name is Ashok and I am 21 years old
>>> obj2.about()
My name is Asmita and I am 20 years old

However, does this process prevent the dynamic addition of an attribute to an object/class? Well, not really.

>>> setattr(obj1marks50)
>>> obj1.marks
50

So, how do we ensure that the object will have only those attributes as per the class definition? The answer is slots .

_slots_

To prevent any further attribute to be added to an object of a class, it carries a variable named as__slots__. This variable is defined before__init__ () method. It is a list of allowed attributes to be initialized by the constructor. The setattr () function will first check if the second argument is in the__slots__list and assign it a new value only if it exists.

Example

#myclass.py
class MyClass:
          __slots___=['myname', 'myage']
         def__init___(self, name=None, age=None):
                 self.myname=name
                 self.myage=age
def about(self):
               print ('My name is { } and I am { } years old1.format(self.myname,self.myage))

Import the modified class and check the effect of__slots___variable.

Example

>>> from myclass import MyClass
>>> obj1=MyClass('Ashok', 21)
> > > obj1.about( )
My name is Ashok and I am 21 years old
>>> setattr(obj1, 'marks', 50) #new attribute not allowed
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute 'marks'
>>> setattr(obj1, 'myage', 25) #value of existing module can be modified
>>> obj1.about()
My name is Ashok and I am 25 years old

 

Leave a Comment