father class name

Chris Rebert clp2 at rebertia.com
Mon Dec 31 08:27:39 CET 2012


On Sun, Dec 30, 2012 at 8:18 PM, contro opinion <contropinion at gmail.com> wrote:
> 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?

The fact that `haha(object)` is textually part of the *declaration*
`class haha(object):` has no bearing on how one instantiates an
instance of the class `haha`.
In the `class` statement, `haha` is being declared to be a subclass of
class `object` (that's what it means for `object` to be in the
parentheses after the class name in a `class` statement; the syntax is
"class <classname>(<base classes>):").

In the first part of the *expression* `haha().theprint()`, you are
using the function-call operator on the `haha` class itself, which has
the effect of instantiating it; since you gave no arguments in the
function call, haha's initializer (i.e. its __init__() method) was
given no arguments. Since you didn't define an __init__() method for
haha, haha inherited the default __init__() method from class
`object`, which takes no arguments, so your call was fine and worked
as expected.

By contrast, in the first part of the *expression*
`haha(object).theprint()`, you passed an argument (namely, `object`).
Since __init__() wasn't expecting any arguments whatsoever, you
therefore got an error.

The parentheses in a `class` statement do NOT signify a function call;
they are part of the syntax of the `class` statement itself.

Cheers,
Chris
--
Note: I'm oversimplifying things a bit for the sake of understandability.



More information about the Python-list mailing list