__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
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…
@rnd42 : That was a good one. Thanks for the explanation.