git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Calling an instance method defined without any 'self' parameter


On Thu, Oct 4, 2018 at 10:20 PM Thomas Jollans <tjol at tjol.eu> wrote:

> 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)
> >
>
> 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:
>

Thought a little about it. A.__dict__['foo']() works! Thanks.


>
> Python 3 is much nicer.
>
> Cheers,
> Thomas
> --
> https://mail.python.org/mailman/listinfo/python-list
>