ygetarts
ygetarts

Reputation: 944

Python class variable with function call?

I'm new to python and going through someone's code to see and how it works. I've come across something I don't really understand. There is an API class and in it are what looks like class variables (?) that look like this:

class API(object):
    ...
    ping = bind_api(
       path='/user/ping',
       allowed_param=['lat', 'lon'],
       method='POST',
    )
    ...

Which looks like it calls a function in another file called binder, which looks like this

def bind_api(**config):

   class APIMethod(object):
      path = config['path']
      allowed_param = config.get('allowed_param', [])
    ......

I really don't get what is going on? Is this a class variable? What gets assigned to 'ping'? How do I access it?

I'm trying to write a class that uses this library, and I have something like this:

import api

class ApiTest():

   def Test():
        testApi = api.API()                       
        print "Ping ",dir(testApi.ping)
        print testApi.ping

But neither of those print statements really give me more insight into what is happening, or what the 'ping' variable holds, or what I'm supposed to do with it (or the other variables in the class that are doing the same thing)

Upvotes: 1

Views: 710

Answers (1)

Patrick Maupin
Patrick Maupin

Reputation: 8127

Yes, that looks like a class variable. As long as a class variable is not shadowed by an instance variable, you can access it by name from any instance, or you can access it directly from the class type. For example:

>>> class Foo(object):
...     bar = 1
... 
>>> x = Foo()
>>> y = Foo()
>>> x.bar = 3
>>> Foo.bar
1
>>> y.bar
1
>>> x.bar
3

When the class is compiled, the code inside the class -- for example, the call that sets up your ping variable, in this case, is executed. This gives you the exact same ping for every class instance, as shown above.

Sometimes people don't intend for classes to actually be instantiated. They can, like modules, merely be namespaces designed to hold related variables. So it may be that client code is expected to always do something with API.ping.

As far as what goes in it -- you'll have to track down and understand the bind_api function it is calling in order to figure that out.

Upvotes: 1

Related Questions