0

Possible Duplicate:
Class method differences in Python: bound, unbound and static

class A:
    def foo():
        print 'hello world'
    def foo1(self):
        self.foo()

a = A()
a.foo1()

I was looking at using some function which was private to that class. I suppose the only way for that is to go by convention: prefixing an '_' in front of that function name, and still having the first argument as self

But is foo() completely useless?

Community
  • 1
  • 1
deostroll
  • 11,661
  • 21
  • 90
  • 161
  • You can get the function out from the bound method with `a.foo.im_func` -- but the right way to do this is to make it a `@staticmethod`. – Katriel Jan 03 '13 at 09:08

3 Answers3

2

For all uses that matter, yes. You can get the raw function via the various attributes on the method, but there's still little point in having something like that in the class.

>>> A.foo.im_func()
hello world
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

Try calling A.foo(). It'll output 'hello world'.

Note that this will only work in Python 3, since in Python 2 it raises a TypeError.

Volatility
  • 31,232
  • 10
  • 80
  • 89
0

Yes, it is pretty much useless. In Python 2.x the only way to call it without throwing an exception would be to extract the function out of the internals of the class and then call it. In Python 3.x (assuming you converted the print) you could call A.foo() directly.

If foo() really doesn't need the self argument then it doesn't need to be a method: just make it a function in the same module as the class is defined.

Duncan
  • 92,073
  • 11
  • 122
  • 156