-2

I'm trying to have the Child class call and use the Parent's __init__method, what are some other ways to do this other than using the super() method in the Child? I was told to avoid using super() is possible hence I want to know.

# -*- coding: utf-8 -*-

class Room(object):

    def __init__(self, current_room):
        self.current_room = current_room
        print("You are now in Room #{}".format(self.current_room))

class EmptyStartRoom(Room):

    def __init__(self, current_room=1):
        super().__init__(current_room)

class ChestRoomKey1(Room):

    def __init__(self, current_room=2):
        super().__init__(current_room)

a_room = EmptyStartRoom()
other_room = ChestRoomKey1()

From the code above I get:

You are now in Room #1

You are now in Room #2

Kazan
  • 5
  • 3
  • 2
    Why would you want to avoid using `super()`? – Blender Apr 17 '17 at 22:33
  • @Blender I was told there are goods and bads of using super() so as a beginner if I'm not sure what I'm doing I should avoid using it if possible. Maybe that's not the case? – Kazan Apr 17 '17 at 22:41

2 Answers2

0

You can directly call the base class while also passing the self argument:

# -*- coding: utf-8 -*-
class Room(object):    
    def __init__(self, current_room):
        self.current_room = current_room
        print("You are now in Room #{}".format(self.current_room))

class EmptyStartRoom(Room):    
    def __init__(self, current_room=1):
        Room.__init__(self, current_room)

class ChestRoomKey1(Room):    
    def __init__(self, current_room=2):
        Room.__init__(self, current_room)

a_room = EmptyStartRoom()
other_room = ChestRoomKey1()

You should also check out this post, telling you why you should consider using super() when you start doing multi-inheritance, but for now, both ways are fine.

Community
  • 1
  • 1
Taku
  • 31,927
  • 11
  • 74
  • 85
0

Don't try to find alternatives.

They may be possible but you'll end up hardcoding superclasses (see @abccd answer) or using "your own MRO solution". But avoiding super() will turn into a maintenance nightmare in the long run (and it's harder to implement right now).

In your case you're doing everything right! The example is a bit weird because the only difference between the __init__ methods is a default value for an argument but I guess that was just to illustrate the problem, right?

MSeifert
  • 145,886
  • 38
  • 333
  • 352