1

I'm trying to learn inheritance concept in python. I have an Employee class and derivative class Executive.

class Employee:
    'Class defined for employee'

    def __init__(self, name, dept, salary):
        self.name = name
        self.dept = dept
        self.salary = salary

Subclass

class Executive(Employee):

    def __init__(self, name, dept, salary, hascar):
        Employee.__init__(name, dept, salary)
        self.hascar = hascar

has car is a Boolean passed into the constructor, However this will give me an error:

File "I:\Python_practicals\com\python\oop\Executive.py", line 7, in init Employee.init(name, dept, salary) TypeError: init() missing 1 required positional argument: 'salary'

When I try to Instantiate an object of Executive.
emp4 = Executive("Nirmal", "Accounting", 150000, True)

0

2 Answers 2

7

While __init__ is an instance method, you're calling it on the class rather than on an instance. This invocation is called unbound, because it is not bound to an instance. Because of this, you need to explicitly pass self:

class Executive(Employee):
    def __init__(self, name, dept, salary, hascar):
        Employee.__init__(self, name, dept, salary)
#                         ^^^^
        self.hascar = hascar

The recommended way, however, is to use super:

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.

With super your code would look like this:

class Executive(Employee):

    def __init__(self, name, dept, salary, hascar):
        super(Executive, self).__init__(name, dept, salary)
#       ^^^^^^^^^^^^^^^^^^^^^^
        self.hascar = hascar

Python 3 adds some syntactic sugar to make this common parent class invocation simpler:

class Executive(Employee):

    def __init__(self, name, dept, salary, hascar):
        super().__init__(name, dept, salary)  # Py 3
#       ^^^^^^^
        self.hascar = hascar
Sign up to request clarification or add additional context in comments.

3 Comments

In case python3 super() has much simpler syntax. super().__init__(name, dept, salary)
I'm aware, but the OP tagged the question Python 2.7 so I have started with the compatible syntax.
Oh haven't seen that. Sorry !. he also tagged python 3.x for some reason
1

In Python 3.x
Use super() keyword. This will let you avoid typing the Base class explicitly. makes the code more maintainable.

class Executive(Employee):

    def __init__(self, name, dept, salary, hascar):
        super().__init__(name, dept, salary)
        self.hascar = hascar

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.