BPL*_*BPL 52 python python-2.x python-2.7
我收到了这个错误
TypeError:super()至少需要1个参数(给定0)
在python2.7.11上使用此代码:
class Foo(object):
def __init__(self):
pass
class Bar(Foo):
def __init__(self):
super().__init__()
Bar()
Run Code Online (Sandbox Code Playgroud)
使其工作的解决方法是:
class Foo(object):
def __init__(self):
pass
class Bar(Foo):
def __init__(self):
super(Bar, self).__init__()
Bar()
Run Code Online (Sandbox Code Playgroud)
似乎语法是特定于python 3.那么,在2.x和3.x之间提供兼容代码并避免发生此错误的最佳方法是什么?
Mar*_*ers 49
是的,0参数语法特定于Python 3,请参阅Python 3.0和PEP 3135中的新功能 - New Super.
在Python 2和必须跨版本兼容的代码中,只需坚持传递类对象和实例.
是的,有一些"backports"可以super()
在Python 2 中创建无争议版本的工作(如future
库),但是这些需要大量的hacks,包括对类层次结构的完整扫描以找到匹配的函数对象.这既脆弱又缓慢,根本不值得"方便".
这是因为python版本。使用[python --version]检查您的python版本,可能是2.7
In 2.7 use this [ super(baseclass, self).__init__() ]
Run Code Online (Sandbox Code Playgroud)
class Bird(object):
def __init__(self):
print("Bird")
def whatIsThis(self):
print("This is bird which can not swim")
class Animal(Bird):
def __init__(self):
super(Bird,self).__init__()
print("Animal")
def whatIsThis(self):
print("THis is animal which can swim")
a1 = Animal()
a1.whatIsThis()
Run Code Online (Sandbox Code Playgroud)
> In 3.0 or more use this [ super().__init__()]
Run Code Online (Sandbox Code Playgroud)
class Bird(object):
def __init__(self):
print("Bird")
def whatIsThis(self):
print("This is bird which can not swim")
class Animal(Bird):
def __init__(self):
super().__init__()
print("Animal")
def whatIsThis(self):
print("THis is animal which can swim")
a1 = Animal()
a1.whatIsThis()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
63922 次 |
最近记录: |