staticmethod and setattr
Jean-Michel Pichavant
jeanmichel at sequans.com
Mon Mar 15 14:25:00 EDT 2010
Am Montag, den 15.03.2010, 05:42 -0700 schrieb Michael.Lausch:
>> On Mar 15, 11:40 am, Steven D'Aprano <st... at REMOVE-THIS-
>> cybersource.com.au> wrote:
>>
>>> On Mon, 15 Mar 2010 01:43:02 -0700, Michael.Lausch wrote:
>>>
>>>> Hi,
>>>>
>>>> I managed to get confused by Python, which is not such an easy task.
>>>>
>>>> The problem i have is rooted in marshalling, JSON and Dojo. I need some
>>>> static class in function with the name "$ref" i tried:
>>>> class Foo(object):
>>>> @staticmethod
>>>> def _ref(o):
>>>> pass
>>>>
>>>> setattr(Foo, "$ref", Foo._ref)
>>>>
>>> That doesn't work as expected:
>>>
>>>
>>>>>> Foo.__dict__['_ref'] is Foo.__dict__['$ref']
>>>>>>
>>> False
>>>
>>> Try this instead:
>>>
>>>
>>>>>> setattr(Foo, "$ref", Foo.__dict__['_ref'])
>>>>>> Foo.__dict__['_ref'] is Foo.__dict__['$ref']
>>>>>>
>>> True
>>>
>> Now I'm trying to understand why this is the case.
>> How is Foo.__dict__['_ref'] different from Foo._ref?
>> Shouldn't it return the same attribute?
>>
>> And after further experiments i found out that a making
>> Foo._ref a classmethod does work with my first approach.
>>
>>
When you declared _ref as static, a static object has been stored in Foo.
Using Foo.__dict__ you can access this static object, which is *not* the
_ref function
Using Foo._ref, you trigger the lookup mechanism which do much more than
accessing the dict. Especially, if it finds a __get__ method in the
object, it will return the __get__ result instead of the object itself.
Foo._ref is equivalent in your case to
Foo.__dict__['_ref'].__get__(None, Foo)
JM
More information about the Python-list
mailing list