Alex Kleider <aklei...@sonic.net> writes: > I was hoping that it would be possible to create a function > that would do the following: > > def my_name(some_object): > return some_object.__name__
That hope is understandable. It is also easy to be confused about why such a feature doesn't exist; after all, it works for functions and classes and modules (oh my!):: >>> def foo(): pass ... >>> foo.__name__ 'foo' >>> class Bar: pass ... >>> Bar.__name__ 'Bar' >>> import sys >>> sys.__name__ 'sys' So why not arbitrary objects? >>> spam = 4 >>> spam.__name__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'int' object has no attribute '__name__' The answer is that functions, classes, and modules are all *defined*, and (normally) have exactly one canonical name established at definition time. Arbitrary objects are merely *instantiated*, without that definition step. Quite commonly they are used with no name bound to them; so the behaviour of most objects does not have ‘__name__’ in the API. If you would like to make a class that has that attribute on all its instances, feel free. But you need to figure out how the instance detects its own name! class LockeanThing: """ An object that knows the name by which others refer to it. """ def __init__(self): self.__name__ = ??? > But I see what I think you and others have been trying to explain to > me: that the expression some_object.__name__, if it existed, would > indeed be schizophrenic since it would be an attribute of the object, > not the name(s) to which it is bound. That's why I prefer to be clear that the binding operation is one-way only. A reference (such as a name) is bound to an object, the object is not bound to the reference — indeed, the object knows nothing about that relationship. -- \ “I washed a sock. Then I put it in the dryer. When I took it | `\ out, it was gone.” —Steven Wright | _o__) | Ben Finney _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor