Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

python - Subclass - Arguments From Superclass

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

class Superclass(object):
    def __init__(self, arg1, arg2, arg3):
        #Inilitize some variables
        #Call some methods

class Subclass(Superclass):
    def __init__(self):
        super(Subclass, self).__init__()
        #Call a subclass only method

Where I'm having trouble is understanding how arguments are passed between the Superclass and Subclass. Is it necessary to re-list all the Superclass arguments in the Subclass initializer? Where would new, Subclass only, arguments be specified? When I try to use the code above to instantiate a Subclass, it only expects 1 argument, not the original 4 (including self) I listed.

TypeError: __init__() takes exactly 1 argument (4 given)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...