-2

in the below example I want to know when I should use one of them for inherits? I think both are valid so, why sometimes I have to use super if the other way is workable to work with?

class User:

    def __init__(self):
        self._user = "User A"
        pass

class UserA(User):
    _user = "User B"
    def __init__(self):
        super().__init__()


class UserB(User):
    pass
Medo Abdin
  • 185
  • 2
  • 13
  • https://stackoverflow.com/questions/222877/what-does-super-do-in-python This answers your question. – Abhishek Rai Nov 03 '20 at 05:36
  • @AbrarAhmed this is not exactly what I want to know. you can see the comparison I defined above to know exactly what I mean. but anyway thanks for help. – Medo Abdin Nov 03 '20 at 19:58

2 Answers2

1

You are correct, both are valid. The difference is:

  • UserA: you are overwriting the __init__ method of the ancestor. This is practical if you want to add something during the initialization process. However, you still want to initialize the ancestor, and this can be done via super().__init__(), despite having overwritten the __init__ method.
  • UserB: you are fully using the __init__ of the ancestor you are inheriting from (by not overwriting the __init__ method). This can be used if nothing extra needs to be done during initialization.
Christian Karcher
  • 2,533
  • 1
  • 12
  • 17
0

The super() builtin returns a proxy object (temporary object of the superclass) that allows us to access methods of the base class. For example:

class Mammal(object):
  def __init__(self, mammalName):
    print(mammalName, 'is a warm-blooded animal.')
    
class Dog(Mammal):
  def __init__(self):
    print('Dog has four legs.')
    super().__init__('Dog')

self represents the instance of the class. By using the “self” keyword we can access the attributes and methods of the class in python

Holzer
  • 59
  • 8