[Tutor] The trap of the year

Karim karim.liateni at free.fr
Wed Jan 26 02:12:51 CET 2011


Thanks for the tip Steven.

Regards
Karim

On 01/26/2011 12:39 AM, Steven D'Aprano wrote:
> 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__
> ([],)
>
>
>
>



More information about the Tutor mailing list