staticmethod and setattr

M

Michael.Lausch

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)

but when i do something like this in code:

class B(object):
pass
b = Bar
f = Foo.getattr("$ref")
f(b)

if get the following error
ypeError
unbound method _ref() must be called with Foo instance as first
argument (got Bar instance instead)

I managed to impelemnt it with a unbound, "normal" _ref() function,
but i want one _ref function per
class, because they are a little bit different for each class.

One aproach which i have not tried is:
setattr(Foo, "$ref", Foo._ref.im_func).
maybe this works, but i think this is not a clean aproach.
Any ideas?
 
S

Steven D'Aprano

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
 
M

Michael.Lausch

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,965
Messages
2,570,148
Members
46,710
Latest member
FredricRen

Latest Threads

Top