473,385 Members | 2,015 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

introspection inquiry

Where in the language would one find the intropsection capability to
answer the question: what class am I in?

Example:

class ExistentialCrisis:
def __init__(self, text):
self.spam = text
print 'In the constructor of the %s class' % <whatever>

When the constructor method is invoked, would like to see the following
message:

In the constructor of the ExistentialCrisis class

and I would like to be able to do it without substituting the literal
string 'ExistentialCrisis' for <whatever>.

My question is this: what can be substituted for <whatever> that will
make the example above work?

Jul 18 '05 #1
8 1219
mi************@yahoo.com wrote:
....

My question is this: what can be substituted for <whatever> that will
make the example above work?


self.__class__.__name__
--
Robin Becker
Jul 18 '05 #2
Robin Becker wrote:
self.__class__.__name__


Unless I misunderstood the question, that won't work. That will
give you the name of the class the object is an instance is of.
I think he wants the name of the class the method was defined in.

Here's a way to do that using metaclasses and Python's magic
double-underscore attribute-mangling feature:

"""
class SelfKnowledge(type):
def __init__(cls, name, bases, dict):
setattr(cls, "_%s__%s" % (name, "class_name"), name)
type.__init__(cls, name, bases, dict)

class Nietzsche(object):
__metaclass__ = SelfKnowledge

def __init__(self, text):
self.spam = text
print "In the constructor of the %s class" % self.__class_name

class Kierkegaard(Nietzsche):
def __init__(self, text):
print "Now in the constructor of %s" % self.__class_name
Nietzsche.__init__(self, text)

Nietzsche("Thus Spake Zarathustra")
print

Kierkegaard("Fear and Trembling")
"""

$ python test1.py
In the constructor of the Nietzsche class

Now in the constructor of Kierkegaard
In the constructor of the Nietzsche class
--
Michael Hoffman
Jul 18 '05 #3
> Unless I misunderstood the question, that won't work. That will
give you the name of the class the object is an instance is of.
I think he wants the name of the class the method was defined in.


Where is the difference? The method is defined in a class - and an instance
is created from that class.

This works as expected:

class ExistentialCrisis:
def __init__(self, text):
self.spam = text
print 'In the constructor of the %s class' % self.__class__.__name__
ExistentialCrisis("egal")
--
Regards,

Diez B. Roggisch
Jul 18 '05 #4

"Michael Hoffman" <ca*******@mh391.invalid> wrote in message
news:cv**********@gemini.csx.cam.ac.uk...
Robin Becker wrote:
self.__class__.__name__


Unless I misunderstood the question, that won't work. That will
give you the name of the class the object is an instance is of.
I think he wants the name of the class the method was defined in.


If that's the case, then the inspect module should give
the tools to do it without a great deal of angst. Unfortunately,
it doesn't give you the class that defined the method, just
the class that invoked it.

John Roth
Jul 18 '05 #5
Diez B. Roggisch wrote:
[Michael Hoffman]:
Unless I misunderstood the question, that won't work. That will
give you the name of the class the object is an instance is of.
I think he wants the name of the class the method was defined in.


Where is the difference? The method is defined in a class - and an instance
is created from that class.

This works as expected:

class ExistentialCrisis:
def __init__(self, text):
self.spam = text
print 'In the constructor of the %s class' % self.__class__.__name__
ExistentialCrisis("egal")


Yes, but this doesn't work if you have a subclass:

"""
class ExistentialCrisisSubclass(ExistentialCrisis):
def __init__(self, text):
print "New constructor"
ExistentialCrisis.__init__(self, text)

ExistentialCrisisSubclass("whoa")
"""

gives you:

New constructor
In the constructor of the ExistentialCrisisSubclass class

But the second line is *not* in the constructor of
ExistentialCrisisSubclass, it is in the constructor of ExistentialCrisis.

while I read the original post as saying that he wanted
"ExistentialCrisis" there instead. Indeed this example

--
Michael Hoffman
Jul 18 '05 #6
John Roth wrote:
If that's the case, then the inspect module should give
the tools to do it without a great deal of angst. Unfortunately,
it doesn't give you the class that defined the method, just
the class that invoked it.


Are you saying that the inspect module *should* give you the
tools to do it but does not?
--
Michael Hoffman
Jul 18 '05 #7
Michael Hoffman wrote:
Robin Becker wrote:
self.__class__.__name__

Unless I misunderstood the question, that won't work. That will
give you the name of the class the object is an instance is of.
I think he wants the name of the class the method was defined in.

Here's a way to do that using metaclasses and Python's magic
double-underscore attribute-mangling feature:

"""
class SelfKnowledge(type):
def __init__(cls, name, bases, dict):
setattr(cls, "_%s__%s" % (name, "class_name"), name)
type.__init__(cls, name, bases, dict)

class Nietzsche(object):
__metaclass__ = SelfKnowledge

def __init__(self, text):
self.spam = text
print "In the constructor of the %s class" % self.__class_name

class Kierkegaard(Nietzsche):
def __init__(self, text):
print "Now in the constructor of %s" % self.__class_name
Nietzsche.__init__(self, text)

Nietzsche("Thus Spake Zarathustra")
print

Kierkegaard("Fear and Trembling")
"""

$ python test1.py
In the constructor of the Nietzsche class

Now in the constructor of Kierkegaard
In the constructor of the Nietzsche class


I guess if you're right something along the lines of
import inspect
class A:
_class_name=inspect.currentframe().f_code.co_name
def __init__(self,text,_defining_class_name=_class_nam e):
print 'text=',text,'_defining_class_name=',_defining_cla ss_name

class B(A):
pass
b=B('aaa')

==>text= aaa _defining_class_name= A
could work as well, but if we only need the local name why not just
insert directly.
--
Robin Becker
Jul 18 '05 #8
Robin Becker wrote:
import inspect
class A:
_class_name=inspect.currentframe().f_code.co_name
def __init__(self,text,_defining_class_name=_class_nam e):
print 'text=',text,'_defining_class_name=',_defining_cla ss_name

class B(A):
pass
b=B('aaa')
That won't work, if you, say, wanted to print out the name of the
class the constructor was defined in for a whole chain of
constructors. Which is about the only case I can think of where
this would be useful.
could work as well, but if we only need the local name why not just
insert directly.


To be honest, that is what I have done every time I have needed
something like this.

I've only used metaclasses in production code once and I still debate
whether that case is a good idea or not.
--
Michael Hoffman
Jul 18 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Rim | last post by:
Hi, Is there a way to get any sort of introspection which would return the content of an instance *in the order they were declared or executed* as opposed to alphabetical order? Example: ...
4
by: Benjamin Rutt | last post by:
I'm trying to learn about introspection in Python. my ultimate goal is to be able to build a module "text database" of all modules that are in the sys.path, by discovering all candidate modules...
0
by: Steven T. Hatton | last post by:
I suspect the core language is not the level at which introspection should be implemented in C++. That has been the choice of C#, and Java. Both of these languages made some trade-offs to...
4
by: Steven T. Hatton | last post by:
Has there been any substantial progress toward supporting introspection/reflection in C++? I don't intend to mean it should be part of the Standard. It would, nonetheless, be nice to have a...
1
by: James Geurts | last post by:
Hi, Can someone tell me how to test if a field is a const? I am using the FxCop introspection engine, but I suppose I could use reflection if required. for example, the following would return...
2
by: greg.corson | last post by:
Hi, I'm in the process of building a complex system using a sort of "system services" model. I'm looking at putting together various services like serialization, networking, 2D/3D rendering,...
4
by: segue | last post by:
Just Curious.
8
by: R. Bernstein | last post by:
In doing the extension to the python debugger which I have here: http://sourceforge.net/project/showfiles.php?group_id=61395&package_id=175827 I came across one little thing that it would be nice...
3
by: James Stroud | last post by:
Hello, I wanted to automagically generate an instance of a class from a dictionary--which might be generated from yaml or json. I came up with this: # automagical constructor def...
14
by: Dave Rahardja | last post by:
Is there a way to generate a series of statements based on the data members of a structure at compile time? I have a function that reverses the endianness of any data structure: /// Reverse...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
Oralloy
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,...
0
jinu1996
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...

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.