member fns w/o args?

S

Steve Canfield

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?

-sc
 
J

Jeff Epler

fn2 is pretty useless. You could call it as something like
c.__dict__['fn2']() if you really wanted to, though.

Maybe you're trying to find a way to ask about "staticmethod" and
"classmethod", but didn't know the right terms?

http://docs.python.org/lib/built-in-funcs.html#l2h-14
http://docs.python.org/lib/built-in-funcs.html#l2h-63

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD8DBQFA7teoJd01MZaTXX0RAoTIAJ9HLcDI3qOqzZluGUSxgpHZYjssGgCfV3rG
yvVNkMYgDEQcb5a64vxivrM=
=7S/z
-----END PGP SIGNATURE-----
 
C

Christopher T King

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:
TypeError: unbound method fn2() must be called with c instance as first
argument (got nothing instead)
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:
in 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.
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top