If you say "Class._name__" in Python class, the class name appears, but isn't there a variable called "_name__" in the class name space?

Asked 2 years ago, Updated 2 years ago, 21 views

For example,

<<< class M:
         pass
<<< dir(M)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

There's no variable called '_name__'.
But I don't know why I can get 'M' when I run M_name__.

python

2022-09-22 18:01

2 Answers

Python is not a very well-designed language compared to modern languages today, linguistically.

__name__

named special attribute and gave read only attribute.

But Python doesn't have a constant like const, or read only property.

In other words, it can be changed even though it is a read only attribute due to its nature as shown below.

In [1]: class M: 
   ...:     ...:     pass 
   ...:                                                                         
In [2]: M.__name__                                                              
Out[2]: 'M'

In [3]: M.__name__ = 'A'                                                        

In [4]: M.__name__                                                              
Out[4]: 'A'

It's intentionally hidden in the dir or vars function to prevent these side effects. That is, it should be used only as read only. (You can change everything if you hide it, but isn't it meaningless? Why is Python like this? If you say so, there are more than one or two of these ambiguities in Python...)

These special attributes are

https://docs.python.org/3/library/stdtypes.html#special-attributes

You can check it at .


2022-09-22 18:01

https://docs.python.org/3/library/stdtypes.html#definition.__name__

According to this document

Some of these are not reported by the dir() built-in function.

Some of these are not represented by the built-in function dir().

That's what it says.

In fact, the attr of the object marked dir() can also be specified by the user. User-specified means that native primary objects can also be specified, and class _name__ may also be hidden by some intent.


2022-09-22 18:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.