鱼C论坛

 找回密码
 立即注册
查看: 2384|回复: 1

[已解决]python2的super方法和python3的super方法差异问题

[复制链接]
发表于 2016-12-2 11:07:45 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
import random as r
class Fish:
    def __init__(self):
        self.x = r.randint(0,10)
        self.y = r.randint(0,10)
    def move(self):
        self.x -=1
        print '我的位置:' ,self.x,self.y

class Shark(Fish):
    def __init__(self):
        #Fish.__init__(self)
        super(Shark,self).__init__()  ##python2这样使用super会报错,错误提示下面给出了。
        #super().__init__()           ##python3中可以这样使用super不报错,程序能正常运行
        self.hungry = True
        if self.hungry:
            print '好吃'
            self.hungry = False
        else:
            print 'so much'
查了下help文档,应该python2中的super方法是这样使用的,但是执行过程中会报错,有谁知道python2中super方法的具体用法么。这个例子里应该如何修改代码,谢谢哈!

我使用的版本是python2.7.8
D:\python_script>python
Python 2.7.8 (default, Jun 30 2014, 16:08:48)

D:\python_script>python fish.py
我的位置: 9 2
我的位置: 4 10
Traceback (most recent call last):
  File "fish.py", line 39, in <module>
    shark = Shark()
  File "fish.py", line 25, in __init__
    super(Shark,self).__init__()
TypeError: must be type, not classobj

最佳答案
2016-12-2 12:58:07
已解决,在第一个class里加上object即可
class Fish(object)
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-12-2 12:58:07 | 显示全部楼层    本楼为最佳答案   
已解决,在第一个class里加上object即可
class Fish(object)
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-24 07:01

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表