Friday, October 2, 2015

Python Inheritace (accessing the init variables of base class from child class)


>>> class Baseclass(object):
...     def __init__(self, number):
...             self.number = number
...
...
>>> class childclass(Baseclass):

...     def __init__(self, number, number2):
...             self.number2 = number2
...             super(self.__class__, self).__init__(number)
...     def add(self):
...             return self.number + self.number2

>>> c = childclass(2,3)
>>> c.add()
5

Here, Accessing the init variables of base class from inside the child class  (i.e use the values of base class inside the child class)


Reference: http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods



Case 2:  (Here we are accessing the parent variables from the child object, not from the child class/methods)

class base:
...     var1 = "Base class"
...     def __init__(self, number):
...             self.number = 5
...

class child(base):
...     var2 = "child class"
...     def add(self):
...             pass



Output:

 y = child(3)
>>> y.number
5

No comments:

Post a Comment