运行错误,求指教

来源:4-3 Python面向对象-类与运算符

JoshuaShang

2016-11-25 20:20

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回答

  • 晚唱
    2016-11-26 20:04:19
    已采纳

        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)方法里参数用逗号分隔。

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


    晚唱 回复Joshua...

    嘿嘿,不谢,一起加油。

    2016-11-29 17:55:55

    共 2 条回复 >

Python-面向对象

Python面向对象教程,带你深入了解python面向对象特性

71236 学习 · 81 问题

查看课程

相似问题