I'm doing some evil things in Python and I would find it useful to
determine which class a method is bound to when I'm given a method
pointer.
For example:
class Foo(object):
def somemeth(self):
return 42
class Bar(Foo):
def othermethod(sel f):
return 42
Is there some way I can have something like :
findClass(Bar.s omemeth)
that would return the 'Foo' class, and
findClass(Bar.o thermethod)
would return the 'Bar' class?
vic 6 1464
Victor Ng wrote: I'm doing some evil things in Python and I would find it useful to determine which class a method is bound to when I'm given a method pointer.
For example:
class Foo(object): def somemeth(self): return 42
class Bar(Foo): def othermethod(sel f): return 42
Is there some way I can have something like :
findClass(Bar.s omemeth)
that would return the 'Foo' class, and
findClass(Bar.o thermethod)
would return the 'Bar' class?
vic import inspect class Foo(object):
.... def foo(self): pass
.... class Bar(Foo):
.... def bar(self): pass
.... def get_imp_class(m ethod):
.... return [t for t in inspect.classif y_class_attrs(m ethod.im_class) if
t[-1] is method.im_func][0][2]
.... [get_imp_class(m ) for m in [Bar().foo, Bar().bar, Bar.foo, Bar.bar]]
[<class '__main__.Foo'> , <class '__main__.Bar'> , <class '__main__.Foo'> ,
<class '__main__.Bar'>]
but with this approach you will get into trouble as soon as you are using
the same function to define multiple methods. There may be something in the
inspect module more apt to solve the problem -- getmro() perhaps?
Peter
Awesome! I didn't see the getmro function in inspect - that'll do the
trick for me. I should be able to just look up the methodname in each
of the class's __dict__ attributes.
vic
On Fri, 25 Feb 2005 16:29:25 +0100, Peter Otten <__*******@web. de> wrote: Victor Ng wrote:
I'm doing some evil things in Python and I would find it useful to determine which class a method is bound to when I'm given a method pointer.
For example:
class Foo(object): def somemeth(self): return 42
class Bar(Foo): def othermethod(sel f): return 42
Is there some way I can have something like :
findClass(Bar.s omemeth)
that would return the 'Foo' class, and
findClass(Bar.o thermethod)
would return the 'Bar' class?
vic
import inspect class Foo(object): ... def foo(self): pass ... class Bar(Foo): ... def bar(self): pass ... def get_imp_class(m ethod): ... return [t for t in inspect.classif y_class_attrs(m ethod.im_class) if t[-1] is method.im_func][0][2] ... [get_imp_class(m ) for m in [Bar().foo, Bar().bar, Bar.foo, Bar.bar]]
[<class '__main__.Foo'> , <class '__main__.Bar'> , <class '__main__.Foo'> , <class '__main__.Bar'>]
but with this approach you will get into trouble as soon as you are using the same function to define multiple methods. There may be something in the inspect module more apt to solve the problem -- getmro() perhaps?
Peter
-- http://mail.python.org/mailman/listinfo/python-list
Peter Otten wrote: import inspect class Foo(object): ...*****def*foo (self):*pass ... class Bar(Foo): ...*****def*bar (self):*pass ... def get_imp_class(m ethod): ...*****return*[t*for*t*in*insp ect.classify_cl ass_attrs(metho d.im_class) if t[-1] is method.im_func][0][2] ... [get_imp_class(m ) for m in [Bar().foo, Bar().bar, Bar.foo, Bar.bar]] [<class '__main__.Foo'> , <class '__main__.Bar'> , <class '__main__.Foo'> , <class '__main__.Bar'>]
but with this approach you will get into trouble as soon as you are using the same function to define multiple methods. There may be something in
I think it might be better to demonstrate the problem than just to describe
it: def another(self): pass
.... Foo.alpha = another Bar.beta = another get_imp_class(B ar.alpha)
<class '__main__.Foo'> get_imp_class(B ar.beta)
<class '__main__.Foo'>
A name check won't help either:
Foo.alpha.__nam e__
'another'
Peter
In article <ma************ *************** ************@py thon.org>,
Victor Ng <cr*********@gm ail.com> wrote: I'm doing some evil things in Python and I would find it useful to determine which class a method is bound to when I'm given a method pointer.
I don't know where (or if) it's documented, but im_class seems to give
you what you want.
------
class Foo(object):
def x(self):
return 42
f = Foo()
print f.x.im_class
------
king:play$ ./x.py
<class '__main__.Foo'>
I have no idea why it's not __imclass__ or some such, but poking
around with dir() is a great way to explore little nooks and crannies
like this. I just printed dir(Foo().x) and tried stuff that looked
interesting until I found what I (you) wanted.
Another way is to make a simple metaclass, setting an attribute (like
defining_class, or something) on each function object in the class
dictionary.
So I went digging through the documentation more and found the following: http://docs.python.org/ref/types.html
There's a section titled "User-defined methods" which covers all the
im_self, im_class attributes and what they are responsible for.
vic
On 25 Feb 2005 10:42:06 -0800, pe*******@gmail .com <pe*******@gmai l.com> wrote: Another way is to make a simple metaclass, setting an attribute (like defining_class, or something) on each function object in the class dictionary.
-- http://mail.python.org/mailman/listinfo/python-list
--
---
"Never attribute to malice that which can be adequately explained by
stupidity." - Hanlon's Razor This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Ruud de Jong |
last post by:
I have the situation where I need to construct the name
of a static method, and then retrieve the corresponding
function from a class object.
I thought I could just use __getattribute__ for this purpose.
This works fine if I already have an instantiation of the class,
but not when I try this on the class object directly.
A bare bones example:
|
by: Lenard Lindstrom |
last post by:
I was wondering if anyone has suggested having Python determine
a method's kind from its first parameter. 'self' is a de facto
reserved word; 'cls' is a good indicator of a class method
( __new__ is a special case ). The closest to this I could find
was the 2002-12-04 posting 'metaclasses and static methods'
by Michele Simionato. The posting's example metaclass uses the
method's name. I present my own example of automatic method
kind...
|
by: Irmen de Jong |
last post by:
Hi,
I've developed the Metaclass below, because I needed a way
to make a bunch of classes thread-safe.
I didn't want to change every method of the class by adding
lock.aqcuire()..lock.release() around the existing code.
So I made a metaclass that essentially replaces every method
of a class with a 'wrapper' method, that does the locking,
invocation, unlocking.
Is this the right approach? It seems to work fine. But I have
|
by: John M. Gabriele |
last post by:
I've done some C++ and Java in the past, and have recently learned
a fair amount of Python. One thing I still really don't get though
is the difference between class methods and instance methods. I
guess I'll try to narrow it down to a few specific questions, but
any further input offered on the subject is greatly appreciated:
1. Are all of my class's methods supposed to take 'self' as their
first arg?
2. Am I then supposed to call...
|
by: Christopher W. Douglas |
last post by:
I am writing a VB.NET application in Visual Studio 2003. I have written a
method that handles several events, such as closing a form and changing the
visible status of a form. I have some code that applies to all these
events, but I need to have specific code execute when the form closes. The
properties for this method are sender (the originator) and e (event
arguments). I know how to get typeof (sender) to determine what form or...
| |
by: Farshid Lashkari |
last post by:
Hi,
I have an object and I want to check if it is a bound or unbound method,
or neither. I tried using the types module, but it seems as though
types.UnboundMethodType and types.MethodType are equal. How else can I
determine this? BTW, I'm using Python 2.3
Thanks,
Farshid
|
by: venk |
last post by:
Hi,
given below is my interaction with the interpreter.... In one case, i
have created the class method using the "famous idiom"... and in the
other, i have tried to create it outside the class definition... why
isn't the latter working ? (of course, the presence of decorators is a
different issue)....
>>> class D:
.... def f(cls):
.... print cls
....
|
by: Steven D'Aprano |
last post by:
There's some subtle behaviour going on here that I don't really follow.
Class methods apparently aren't classmethods.
.... def method(self, *args):
.... return self, args
.... @classmethod
.... def cmethod(cls, *args):
.... return cls, args
....
|
by: wink |
last post by:
I'd like to determine if a method has been overridden as was asked
here:
http://www.velocityreviews.com/forums/t564224-determining-whether-a-derived-class-overrides-a-virtual-memberfunction.html
The answer was can't do it, but I thought I'd ask here, my test code
is:
#include <iostream>
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |