472,141 Members | 1,332 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,141 software developers and data experts.

Re: Retrieving the name of the class calling an instance method

mercado mercado wrote:
In Python, is it possible for an instance method to know the name of the
class which is calling it?
Well, the class name is in __class__ so changing
'print x' to
'print __class__'
will show foo in both cases, which is in fact the name of the class
which is calling it.

Of course, what you want is the name of the thing chained in front of
that. There are and are not ways of getting to that. Dig into the
traceback module.

But I'd pass a parameter to foo's __init__ such as foo('bar') and
foo('again') and it'd always work.

HTH,

Emile

For example, in the sample below, I would
like for the someMethod method to print the name of the class calling it
("bar" in the first case, "again" in the second).

---------------------------------------
class foo():
def someMethod(self):
print x

class bar():
def __init__(self):
f = foo()
f.someMethod()

class again():
def __init__(self):
f = foo()
f.someMethod()

bar()
again()
---------------------------------------
------------------------------------------------------------------------

--
http://mail.python.org/mailman/listinfo/python-list
Sep 5 '08 #1
0 1008

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Diffident | last post: by
reply views Thread by Diffident | last post: by
3 posts views Thread by Goran Djuranovic | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.