Objects with __name__ attribute
Peter Otten
__peter__ at web.de
Wed Oct 25 03:21:22 EDT 2017
ast wrote:
> Hi,
>
> I know two Python's objects which have an intrinsic
> name, classes and functions.
>
> def f():
> pass
>
>>>> f.__name__
> 'f'
>>>> g = f
>>>> g.__name__
> 'f'
>
> class Test:
> pass
>
>>>> Test.__name__
> 'Test'
>>>> Test2 = Test
>>>> Test2.__name__
> 'Test'
>
> Are there others objects with a __name__ attribute
> and what is it used for ?
>
> Regards
It was used for the object's repr():
$ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(): pass
...
>>> f.__name__ = "spanish inquisition"
>>> f
<function spanish inquisition at 0x7faad26ed7d0>
But this has changed:
$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(): pass
...
>>> f.__name__ = "spanish inquisition"
>>> f
<function f at 0x7f302fc20bf8>
>>> f.__qualname__ = "spanish inquisition"
>>> f
<function spanish inquisition at 0x7f302fc20bf8>
You should be aware that the module name is used to detect the main module:
if __name__ == "__main__":
print("this is run as a script")
More information about the Python-list
mailing list