oop - How to write a class method in Python that captures the name of the instance and apply some action on it -


i don't know if it's possible here want( or dream of...):

class a:      method1:        return      method2:        return else      method3:        return(some_action, the_name_of_instance)      more_methods: 

in words, if class a instantiated as:

inst_a = a("some") 

method3 should know name of instance(inst_a) time , apply action defined user.

therefore, user point of view, action applied onto inst_a method called in inst_a.method3()

this not how python works - single pyobject (an instance) might go number of names, , can't put single name on something:

my_instance = myclass() my_second_instance = my_instance # what's "name" of instance now? there's 2 handles it, now. 

also, there's many cases instance doesn't have name @ - example, if it's created "temporarily" when created directly passed function.

print pickle.dumps(myclass()) # new instance doesn't long-lived name @ 

all in all, think intend break isolation between state of object , reference object -- not idea. if need unique identifier, use built-in id function: id(self).

edit https://stackoverflow.com/users/642070/tdelaney correctly pointed out have careful id(), because have no guarantee after end of life of 1 object, object can't same id, which, way, in cpython memory address of underlyin pyobject.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -