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
249 views
in Technique[技术] by (71.8m points)

Is there any method like __init_subclass__() before python 3.6

When I read Python Cookbook 3rd Edition recipe 9.18, I ran into a class definition with parent Class and some optional argument, and I looked it up. I know that Python 3.6 added a new feature __init_subclass__() method for parent class, but the book is written based on Python 3.3, so what method will take these arguments other than a metaclass?

The class definition is here:

class Spam(Base, debug=True, typecheck=False):
    ...

I know that metaclass can accept other optional arguments in its' __prepare__, __new__, __init__ method, but Base is a parent class, where do these arguments go?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The __init_subclass__ is an addition to Python 3.6 to reduce the need for custom metaclasses, as many of its uses are "overkill". The idea is that each subclass that is created for a (normal, non-meta) base-class that contains an __init_subclass__ method, it willbe called, with the new subclass as first parameter:

class Base:
   def __init_subclass__(subclass, debug=None, typecheck=None, **kwargs):
        # do stuff with the optional debug and typecheck arguments
        # Pass possible arguments not consumed here to superclasses, if any:
        super().__init_subclass__(**kwargs)

And there is no need for a metaclass at all - the __prepare__, __init__ and __new__ of the default metaclass - type - will ignore any named argument passed in this way. But the default __init_subclass__ in object will raise if unknown named arguments reach it - the pattern above will consume these arguments, removing them from kwargs. If you are dealing with unknown named arguments, just process kwargs like a normal dictionary - no need for explicit named parameters in the __init_subclass__.


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

...