-1
class User(object):

    def __init__(self, id_code, name, surname):
        self.id_code = id_code
        self.name = name
        self.surname = surname

class Worker(User):

    def __init__(self, username, password, worker_type):
        super(User, self).__init__()
        self.username = username
        self.password = password
        self.worker_type = worker_type

How i can call constructor with attributes from super class?

ex:

id_code = "test_code"
name = "test_name"
surname = "test_surname"
username = "test_username"
password = "test_pass"
Cœur
  • 37,241
  • 25
  • 195
  • 267
StefanTflch
  • 145
  • 2
  • 14
  • 4
    You need to name *your own class*, not the super class, in `super()`: `super(Worker, self).__init__()`. You also need to pass in the expected arguments explicitly. – Martijn Pieters May 01 '16 at 15:15

1 Answers1

1

First you had a small logical mistake in there which @MartijnPieters already pointed out: The first argument of super should be the current class:

super(Worker, self).__init__()

In order to pass them to the superclass you need to accept these arguments in the subclass. Either by hardcoding:

class User(object):

    def __init__(self, id_code, name, surname):
        self.id_code = id_code
        self.name = name
        self.surname = surname

class Worker(User):

    def __init__(self, id_code, name, surname, username, password, worker_type): # changed
        super(Worker, self).__init__(id_code, name, surname) # changed
        self.username = username
        self.password = password
        self.worker_type = worker_type

or using *args and **kwargs (see for example: correct way to use super (argument passing)). But that's far from being trivial because you need to know which class needs which arguments and how the order should be and what arguments are positional-only or keyword-only or if you want to allow them all as positional-or-keyword-argument. Also you hide the argument(-names).

I would stick to hardcoding the arguments and only if that get's to complicated in the long run to consider switching to *args, **kwargs.

Community
  • 1
  • 1
MSeifert
  • 145,886
  • 38
  • 333
  • 352