为了账号安全,请及时绑定邮箱和手机立即绑定

运行错误,求指教

class Program():
    def __new__(cls,*args,**kwargs):
        print "call_new_method"
        print args
        return super(Program.cls).__new__(cls,*args,**kwargs)
    def __init__(self,name,age):
        print "call_init_method"
        self.name=name
        self.age=age
    def __eq__(self,other):
        if isinstance(other,Program):
            if self.age==other.age:
                return True
            else:
                return False
        else:
            raise Exception("The type of object must be Program")
    def __add__(self,other):
        if isinstance(other,Program):
            return self.age+other.age
        else:
            raise Exception("The type of object must be Program")
   
p1=Program("Thom",63)
p2=Program("Tom",60)
print p1==p2
print p1+p2

代码运行结果为:call_init_method
call_init_method
False
123

为什么觉得__new__方法没有执行 ?

后添加继承object,运行结果为?

call_new_method
('Thom', 63)
Traceback (most recent call last):
  File "D:\Java\myeclipse\workspace\IPython\com\Test\test_operation.py", line 24, in <module>
    p1=Program("Thom",63)
  File "D:\Java\myeclipse\workspace\IPython\com\Test\test_operation.py", line 5, in __new__
    return super(Program.cls).__new__(cls,*args,**kwargs)
AttributeError: type object 'Program' has no attribute 'cls'

并请问cls,self区别

正在回答

1 回答

    def __new__(cls,*args,**kwargs):
        print "call_new_method"
        print args
        return super(Program.cls).__new__(cls,*args,**kwargs)

最后一句行该是return super(Program,cls).__new__(cls,*args,**kwargs)

super(Program, cls)方法里参数用逗号分隔。

(盯着屏幕看了半天。。。。。。


2 回复 有任何疑惑可以回复我~
#1

JoshuaShang 提问者

天,居然标点打错了,感谢
2016-11-29 回复 有任何疑惑可以回复我~
#2

晚唱 回复 JoshuaShang 提问者

嘿嘿,不谢,一起加油。
2016-11-29 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

运行错误,求指教

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信