-2

这是我的哈哈课

class  haha(object):
  def  theprint(self):
    print "i am here"

>>> haha().theprint()
i am here
>>> haha(object).theprint()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object.__new__() takes no parameters

为什么haha(object).theprint()输出错误?

4

3 回答 3

0

这个你的轻微变化的例子haha可能会帮助你了解正在发生的事情。我已经实现__init__了,所以你可以看到它何时被调用。

>>> class haha(object):
...   def __init__(self, arg=None):
...     print '__init__ called on a new haha with argument %r' % (arg,)
...   def theprint(self):
...     print "i am here"
... 
>>> haha().theprint()
__init__ called on a new haha with argument None
i am here
>>> haha(object).theprint()
__init__ called on a new haha with argument <type 'object'>
i am here

如您所见,haha(object)最终object作为参数传递给__init__. 由于您尚未实施__init__,因此您收到错误,因为默认值__init__不接受参数。如您所见,这样做没有多大意义。

于 2012-12-31T18:35:34.947 回答
0

您在实例化时将继承与初始化类混淆了。

在这种情况下,对于您的类声明,您应该这样做

class  haha(object):
    def  theprint(self):
        print "i am here"

>>> haha().theprint()
i am here

因为 haha​​(object) 意味着 haha​​ 继承自 object。在 python 中,不需要这样写,因为默认情况下所有类都继承自 object。

如果您有一个接收参数的init方法,则需要在实例化时传递这些参数,例如

class  haha():
    def __init__(self, name):
        self.name=name
    def theprint(self):
        print 'hi %s i am here' % self.name

>>> haha('iferminm').theprint()
hi iferminm i am here
于 2012-12-31T18:39:40.083 回答
0

class haha(object):表示haha继承自object. 从基本上继承object意味着它是一个新样式的类。

调用haha()会创建一个 的新实例,haha从而调用构造函数,该构造函数将是一个名为 的方法__init__。但是,您没有,因此使用不接受任何参数的默认构造函数。

于 2012-12-31T15:16:11.793 回答