I'm trying to understand the relationship between the variable a Python class object is assigned to and the __name__
attribute for that class object. For example:
In [1]: class Foo(object):
...: pass
...:
In [2]: Foo.__name__ = 'Bar'
In [3]: Foo.__name__
Out[3]: 'Bar'
In [4]: Foo
Out[4]: __main__.Bar
In [5]: Bar
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-5-962d3beb4fd6> in <module>()
----> 1 Bar
NameError: name 'Bar' is not defined
So it seems like I have changed the __name__
attribute of the class but I can't refer to it by that name. I know this is a bit general but could someone explain the relationship between Foo
and Foo.__name__
?
__name__ is a built-in variable which evaluates to the name of the current module. Thus it can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if statement, as shown below.
Double Leading Underscore __var : Triggers name mangling when used in class context. Enforced by the Python interpreter. Single Trailing Underscore var_ : Used by convention to avoid naming conflicts with Python keywords. Double Trailing Underscore __var__ : Indicates special methods defined by Python language.
What is an Class Variable in Python? If the value of a variable is not varied from object to object, such types of variables are called class variables or static variables. Class variables are shared by all instances of a class.
__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .
It's simple. There is no relationship at all.
When you create a class a local variable is created with name you used, pointing at the class so you can use it.
The class also gets an attribute __name__
that contains the name of that variable, because that's handy in certain cases, like pickling.
You can set the local variable to something else, or change the __name__
variable, but then things like pickling won't work, so don't do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With