member fns w/o args?

Christopher T King squirrel at WPI.EDU
Fri Jul 9 13:52:35 EDT 2004


On 9 Jul 2004, Steve Canfield wrote:

> Is fn2() accessible?
> 
> class c:
>   def fn1(self):
>     print "in fn1()"
>   def fn2():
>     print "in fn2()"
> 
> Do member functions with no arguments have any meaning?  

fn2() is accessible, but will result in an error no matter how you try to 
call it: When functions are defined in this manner, Python marks them as 
methods and expects them to be called with a class instance as the first 
argument, and will complain otherwise. fn2(), however, expects no 
arguments, and will complain if it gets any:

>>> c.fn2()
TypeError: unbound method fn2() must be called with c instance as first 
argument (got nothing instead)

>>> c().fn2()     # this is equivalent to c.fn2(c())
TypeError: fn2() takes no arguments (1 given)

You can, however, make these methods useable by declaring them as static 
methods:

class c:
  def fn1(self):
    print "in fn1()"
  def fn2():
    print "in fn2()"

  fn2=staticmethod(fn2)

staticmethod() converts a method that requires a class instance as its 
first argument into one that doesn't, so now you can do this:

>>> c.fn2()
in fn2()

>>> c().fn2()     # now equivalent to c.fn2()
in fn2()

Also of interest to you may be classmethod(), which works like 
staticmethod() but instead causes the method to require a class (rather 
than a class instance) as its first argument.




More information about the Python-list mailing list