user3206440
user3206440

Reputation: 5049

Python Inheritance: what is the difference?

Given a parent class 'A'

Class A(object):
    def __init__(self,a,b):
        self.a = a
        self.b = b

What is the difference between making a subclass 'B' among the below options

Option 1

Class B(A):
    def __init__(self,a,b,c):
        self.a = a
        self.b = b
        self.c = c

Option 2

Class B(A):
    def __init__(self,a,b,c):
        A.__init__(self, a, b)
        self.c = c

Upvotes: 1

Views: 65

Answers (2)

aliasm2k
aliasm2k

Reputation: 901

Your first option initializes members of class A (a and b) as if it was in class B.

The second option uses constructor of A to initialize members of A before initializing members of B.

A better approach to design classes in Python would be

class A(object):
    def __init__(self, a, b):
        self._a = a
        self._b = b

    @property
    def a(self):
        return self._a

    @property
    def b(self):
       return self._b

class B(A):
    def __init__(self, a, b, c):
        super(B, self).__init__(a, b)
        self._c = c

    @property
    def c(self):
        return self._c

The _ in member names mentions that the members should not be accessed directly. The decorator @property provides direct accessors for the members.

Note that members are read only. This class have no setters specified. For example, setter for c can be declared as follows

@c.setter
def c(self, c):
    self._c = c

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599600

In this case, none. But what if A.__init__ did loads of complex logic? You don't want to have to duplicate all that in B.

An enhancement on Option 2 is to use the super() function:

class B(A):
    def __init_(self,a,b,c):
        super(B, self).__init__(a, b)
        self.c = c

Upvotes: 4

Related Questions