在python 3.6之前是否有类似__init_subclass __()的方法 [英] Is there any method like __init_subclass__() before python 3.6
问题描述
当我阅读Python Cookbook 3rd Edition食谱9.18时,我遇到了一个带有父类和一些可选参数的类定义,然后我进行了查找.我知道Python 3.6为父类添加了新功能 __ init_subclass __()
方法,但是本书是基于Python 3.3编写的,因此,除了 metaclass 之外,哪种方法将采用这些参数?代码>?
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
?
类定义在这里:
class Spam(Base, debug=True, typecheck=False):
...
我知道元类可以在其 __ prepare __
, __ new __
, __ init __
方法中接受其他可选参数,但可以接受 Base code>是父类,这些参数在哪里?
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?
推荐答案
就像往常一样,它们转到元类的 __ prepare __
方法.仅仅因为 Base
没有指定一个元类并不意味着它没有一个.默认的元类是 type
.
They go to the metaclass's __prepare__
method, just like always. Just because Base
hasn't specified a metaclass doesn't mean it doesn't have one. The default metaclass is type
.
在Python 3.6中为 type
添加 __ init_subclass __
只是节省了您定义自定义元类的工作,以实现与 __ init_subclass __
你自己.
The addition of __init_subclass__
to type
in Python 3.6 just saves you the effort of defining a custom metaclass in order to implement an equivalent to __init_subclass__
yourself.
这篇关于在python 3.6之前是否有类似__init_subclass __()的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!