Calling an instance method defined without any 'self' parameter
On 2018-10-04 10:25, Ibrahim Dalal wrote:
> class A:
> def foo():
> print 'Hello, world!'
> a = A()print A.foo # <unbound method A.foo>print a.foo #
> <bound method A.foo of <__main__.A instance at 0x7efc462a7830>>print
> type(A.foo) # <type 'instancemethod'>
> a.foo() # TypeError: foo() takes no arguments (1 given)
> A.foo() # TypeError: unbound method foo() must be called
> with A instance as first argument (got nothing instead)
> Clearly, foo is an instance method. I know one should use @staticmethod for
> declaring a method static. The question here is, given the above code, is
> there any way to call foo?
Yes: use Python 3!
Python 3.7.0 (default, Jun 28 2018, 13:15:42)
[GCC 7.2.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
... def foo():
<function A.foo at 0x7fed562b0048>
> Python 2.7
There is a way in Python 2 as well, and I'm sure someone else will
demonstrate. I won't. It's easy enough to discover if you know that it
should exist. I'll just tell you that Python 3 is much nicer:
Python 3 is much nicer.