Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python class variable name vs __name__

Tags:

python

class

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__?

like image 673
ACV Avatar asked Aug 20 '13 03:08

ACV


People also ask

What is the __ name __ variable in Python?

__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.

What is difference between _ and __ in Python?

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.

Is class A variable name in Python?

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.

What does __ class __ mean in Python?

__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 .


1 Answers

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.

like image 129
Lennart Regebro Avatar answered Oct 12 '22 11:10

Lennart Regebro