How to get a reference of the 'owner' class to which a method belongs in Python 3.X?
Richard Thomas
chardster at gmail.com
Sat Mar 17 03:34:57 EDT 2012
On Saturday, 17 March 2012 05:30:34 UTC, Cosmia Luna wrote:
> I'm porting my existing work to Python 3.X, but...
>
> class Foo:
> def bar(self):
> pass
>
> mthd = Foo.bar
>
> assert mthd.im_class is Foo # this does not work in py3k
mthd.im_class is the class of mthd.im_self not the class that defined the method.
>
> So, how can I get a reference to Foo? This is important when writing
> decorators, the only way I can think out is:
Not sure what sort of decorators you're writing. Examples?
You can achieve this with metaclasses but if you're using classes from someone else's code this doesn't necessarily work. Something in inspect module can probably do the trick, check the docs. Frankly though it sounds messy no matter what. It might be better to find an alternative to knowing the class.
> class Foo:
> def bar(self):
> 'Foo' # manually declare the owner class
> pass
>
> mthd = Foo.bar
>
> assert mthd.__globals__[mthd.__doc__] is Foo # this works
>
> class Child(Foo):
> def bar(self):
> 'Child' # I have to override all method defined by bar but do nothing
> pass
>
> child_mthd = Child.bar
>
> assert child_mthd.__globals__[child_mthd.__doc__] is Child # this works
>
> But the code above is quite ugly and abuses the __doc__. Is there any
> equivalent in py3k of im_class?
>
> Thanks,
> Cosmia
More information about the Python-list
mailing list