2012-12-31 141 views
-2

这里是我的,哈哈类使用`object`实例化自定义类

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()得到错误的输出?

+9

你在期待'哈哈(对象)'做什么? – BrenBarn

+3

OP令人困惑的继承与实例化 – inspectorG4dget

+0

虽然这是一个新手问题,但我认为作者正在尝试一个很好的问题,这是一个可以理解的混淆。在我的书中,不是一个downvote的理由。 –

回答

0

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

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

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__不接受参数。正如你所看到的,这样做没有多大意义。

0

你很混淆在实例化时初始化一个类的继承。

在这种情况下,你的类声明,你应该做的

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

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

由于哈哈(对象)是指从哈哈对象继承。在python中,没有必要写这个,因为所有的类都默认从对象继承。

如果您有接收参数的初始化方法,你需要通过这些参数实例时,例如

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 
相关问题