使用“object”实例化自定义类

2024-04-25 00:26:48 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的哈哈课

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()输出错误?你知道吗


Tags: selfmosthereobjectdefcallamclass
3条回答

这个关于你的haha的轻微变化的例子可以帮助你理解正在发生的事情。我已经实现了^{},所以您可以看到它何时被调用。你知道吗

>>> 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__不接受参数。如你所见,这样做没有多大意义。你知道吗

在实例化时,您将继承与初始化类混淆了。你知道吗

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

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

class haha(object):表示hahaobject继承。从object继承基本上意味着它是一个新样式的类。你知道吗

调用haha()会创建一个haha的新实例,并因此调用构造函数,它将是一个名为__init__的方法。但是,您没有这样的构造函数,因此使用了不接受任何参数的defaul构造函数。你知道吗

相关问题 更多 >