"Timothy L. Robertson" <timothyr at timothyr.com> wrote in message news:3aecaef9.340108430 at news.mindspring.com... > Hi Everyone, > > I've been enjoying learning Python very much, but have hit a little > snag. I want a way to find out the name of a class instance from a > method. eg. > > >>>classinstance=MyClass() > >>>classinstance.myname() > 'classinstance' > > Is there a way to do this? Python's Frequently Asked Questions (FAQ) are a very useful resource. You are likely to find reasonable answers to most questions which ARE frequently asked, such as this one. Specifically, see http://www.python.org/doc/FAQ.html#4.97 What that FAQ doesn't say is that you CAN easily write functions that will look for (all occurrences/first occurrence) of a certain value (AKA object) in a set of variables (which is, after all, just a dictionary). For example: def oneName(object, vars): for name, value in vars.items(): if value is object: return name return None to be called as oneName(classinstance, vars()) if you need "just any name" (be it local or global), oneName(classinstance, locals()) if you need specifically a local variable name for the instance, oneName(classinstance, globals()) if you need a global variable name in the current module, oneName(classinstance, dir(amod)) if you need it in module object amod, and so on. It *IS* possible to play "black magic" tricks so the function will be able to use the *caller's* locals or globals by default, but "black magic as a way of life" is *NOT* a programming approach that can be recommended (either in Python, or in any other language)... Alex
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4