-2

here is my haha class

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

why haha(object).theprint() get wrong output?

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
Bqsj Sjbq
  • 1,231
  • 1
  • 12
  • 9

3 Answers3

0

class haha(object): means that haha inherits from object. Inheriting from object basically means that it's a new-style class.

Calling haha() creates a new instance of haha and thus calls the constructor which would be a method named __init__. However, you do not have one so the defaul constructor is used which does not accept any parameters.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
0

This example of a slight change of your haha may help you to understand what is happening. I've implemented __init__ so you can see when it is called.

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

As you can see, haha(object) ends up passing object as a parameter to __init__. Since you hadn't implemented __init__, you were getting an error because the default __init__ does not accept parameters. As you can see, it doesn't make much sense to do that.

Community
  • 1
  • 1
Phil Frost
  • 3,668
  • 21
  • 29
0

You're confusing Inheritance with initializing a class when instantiate.

In this case, for your class declaration, you should do

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

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

Because haha(object) means that haha inherits from object. In python, there is no need to write this because all classes inherits from object by default.

If you have an init method which receives parameters, you need to pass those arguments when instantiating, for example

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
iferminm
  • 2,019
  • 19
  • 34