Why should I use the __prepare__ method to get a class' namespace?

穿精又带淫゛_ 提交于 2019-12-03 05:59:40

Yes, there are risks.

At least two reasons exist for getting the new namespace by calling __prepare__ instead of doing type(clsdict)():

  • When running on Python 2 clsdict is a dict, and the original __prepare__ never ran to begin with (__prepare__ is Python 3 only) -- in other words, if __prepare__ is returning something besides a normal dict, type(clsdict)() is not going to get it.

  • Any attributes set by __prepare__ on the clsdict would not be set when using type(clsdict)(); i.e. if __prepare__ does clsdict.spam = 'eggs' then type(clsdict)() will not have a spam attribute. Note that these attributes are on the namespace itself for use by the metaclass and are not visible in the namespace.

To summarize: there are good reasons to use __prepare__() to obtain the proper class dictionary, and none for the type(clsdict)() shortcut.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!