__name__ for Python class and Python function

This is my first post in the series of small random learnings.

The attribute __name__ is by default present in every python function. But suprisingly an object of a class doesnt have this attribute unless specifically specified.

class example():
    def classFunction():
        return "test"

obj = example()
print obj.__name__  #This is an error

On the other hand ,

def functionA():
    return "A"
def functionB(params):
    return params.__name__

print functionB(functionA) # prints functionA

3 thoughts on “__name__ for Python class and Python function

  1. An object doesn’t have a name because you can create objects without a defined name, for example:

    Class a(object):
    def hello(self):
    print(‘Hello World!’)

    if __name__ == ‘__main__’:
    a().hello() # This is an unnamed instance of class ‘a’.

    Classes however are defined with a declared name similarly to functions. That’s why there is no obj.__name__ but you can find obj.__class__.__name__ on all objects. I hope that helps…

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s