self naming class?
Serge Rey
serge at rohan.sdsu.edu
Thu Oct 18 08:05:20 EDT 2001
i'm trying to create a class that assigns a name attribute in such a way
that the name is set equal to the name of the instance. for example:
test = MyClass()
so that test.name == "test"
i want to get around having to pass the name as an argument to the
constructor:
test = MyClass("test")
i thought the following would work, but my logic is off since the
nameSelf method only works when called outside the __init__. i also
realize that eval and searching the global namespace are probably not
the brightest ways to attempt this, but i'm stuck.
any suggestions for how to accomplish this would be appreciated.
class MyClass:
"""Self-naming class."""
def __init__(self,values):
self.values = values
self.id = id(self)
self.nameSelf()
def nameSelf(self):
globalKeys = globals().keys()
globalIds = [id(eval(x)) for x in globalKeys]
self.globalIds = globalIds
try:
myNamesId = globalIds.index(self.id)
self.name = globalKeys[myNamesId]
except:
self.name = None
if __name__ == '__main__':
data = range(100)
test = MyClass(data)
print test.name
test.nameSelf()
print test.name
--
Sergio J. Rey http://typhoon.sdsu.edu/rey.html
GPG fingerprint = 16DB 4934 E0F1 B386 AE81 D379 914C 33E5 F690 95DF
"Nobody in football should be called a genius. A genius is a guy
like Norman Einstein." - Joe Theismann
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 240 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20011018/7819e47d/attachment.sig>
More information about the Python-list
mailing list