[Tutor] The trap of the year
Steven D'Aprano
steve at pearwood.info
Wed Jan 26 00:39:24 CET 2011
Karim wrote:
>
> Hello Bob,
>
> I know this fact for function but in this case this is not a function
> but a constructor method of a class.
Methods *are* functions. (Technically, they are lightweight wrappers
around functions.) They are treated exactly the same by Python. The
"constructor method" __init__ is treated not special. You can easily see
this by printing the function from *inside* the class, before it gets
wrapped by the class machinery:
>>> class Test: # From Python 3, Python 2 may be a bit different.
... def __init__(myname, arg=[]):
... pass
... print(__init__)
... print(__init__.__defaults__)
...
<function __init__ at 0xb7c1de2c>
([],)
And there you can clearly see the list used as a default value.
It is a little bit harder from outside, because the function is wrapped
in a method-wrapper, but not that hard:
>>> instance = Test()
>>> instance.__init__.__func__
<function __init__ at 0xb7c1de2c>
>>> instance.__init__.__func__.__defaults__
([],)
--
Steven
More information about the Tutor
mailing list