Python扩展 – 使用super()Python 3与Python 2
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python扩展 – 使用super()Python 3与Python 2,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1604字,纯文字阅读大概需要3分钟。
内容图文
![Python扩展 – 使用super()Python 3与Python 2](/upload/InfoBanner/zyjiaocheng/715/c2c1dd087f914a27a86f1bb033d08e61.jpg)
本来我想问this question,但后来我发现之前已经想过……
谷歌搜索我发现这个extending configparser的例子.以下与Python 3一起使用:
$python3
Python 3.2.3rc2 (default, Mar 21 2012, 06:59:51)
[GCC 4.6.3] on linux2
>>> from configparser import SafeConfigParser
>>> class AmritaConfigParser(SafeConfigParser):
... def __init_(self):
... super().__init__()
...
>>> cfg = AmritaConfigParser()
但不是Python 2:
>>> class AmritaConfigParser(SafeConfigParser):
... def __init__(self):
... super(SafeConfigParser).init()
...
>>> cfg = AmritaConfigParser()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __init__
TypeError: must be type, not classob
然后我读了一下Python New Class和Old Class样式(例如here).
现在我想知道,我能做到:
class MyConfigParser(ConfigParser.ConfigParser):
def Write(self, fp):
"""override the module's original write funcition"""
....
def MyWrite(self, fp):
"""Define new function and inherit all others"""
但是,我不应该打电话给init吗?这在Python 2中是等效的:
class AmritaConfigParser(ConfigParser.SafeConfigParser):
#def __init__(self):
# super().__init__() # Python3 syntax, or rather, new style class syntax ...
#
# is this the equivalent of the above ?
def __init__(self):
ConfigParser.SafeConfigParser.__init__(self)
解决方法:
在Python 3中引入了> super()(不带参数)(以及__class__):
super() -> same as super(__class__, self)
所以这将是新风格类的Python 2等价物:
super(CurrentClass, self)
>对于旧式课程,您可以随时使用:
class Classname(OldStyleParent):
def __init__(self, *args, **kwargs):
OldStyleParent.__init__(self, *args, **kwargs)
内容总结
以上是互联网集市为您收集整理的Python扩展 – 使用super()Python 3与Python 2全部内容,希望文章能够帮你解决Python扩展 – 使用super()Python 3与Python 2所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。