Subclass - Arguments From Superclass

后端 未结 1 1927
暗喜
暗喜 2020-12-29 22:01

I\'m a little confused about how arguments are passed between Subclasses and Superclasses in Python. Consider the following class structure:

class Superclass         


        
相关标签:
1条回答
  • 2020-12-29 22:27

    There's no magic happening! __init__ methods work just like all others. You need to explicitly take all the arguments you need in the subclass initialiser, and pass them through to the superclass.

    class Superclass(object):
        def __init__(self, arg1, arg2, arg3):
            #Initialise some variables
            #Call some methods
    
    class Subclass(Superclass):
        def __init__(self, subclass_arg1, *args, **kwargs):
            super(Subclass, self).__init__(*args, **kwargs)
            #Call a subclass only method
    

    When you call Subclass(arg1, arg2, arg3) Python will just call Subclass.__init__(<the instance>, arg1, arg2, arg3). It won't magically try to match up some of the arguments to the superclass and some to the subclass.

    0 讨论(0)
提交回复
热议问题