简体   繁体   中英

what is the difference between super and inheritance by passing it alone as an object?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM