[python] Difference between variables and self. Variables in class

instance.name

When calling a class variable, call it with * instance * .name, There are two types of callees.

name


class foo:
    name1 = 'test1'
    def __init__(self):
        self.name2 = 'test2'

bar = foo()
print(bar.name1)
# => test1
print(bar.name2)
# => test2

The values of these two can be changed in the same way.

bar.name1 = 'huga'
bar.name2 = 'hogehoge'
print(bar.name1)
# => huga
print(bar.name2)
# => hogehoeg

However, the behavior changes as follows.

print(bar.__class__.name1)
# => test1
print(bar.__class__.name2)
# => AttributeError

What is the cause of this? Actually, there are two types of variables that a class has. One is an ordinary class variable. The other is a dict variable that exists as a base member of the class.

name


class foo:
    name1 = 'test1'
    def __init__(self):
        self.name2 = 'test2'

bar = foo()
print(bar.__dict__)
# => {'name2':'test2'}
bar.name1 = 'hoge'
print(bar.__dict__)
# => {'name2':'test2','name1':'hoge'}

Calling methods such as * instance * .name preferentially display \ _ \ _ dict \ _ \ _ [name]. Call \ _ \ _ class \ _ \ _. name only if \ _ \ _dict \ _ \ _ [name] does not exist.

If you want to use a class variable as an initial value or an unchanged value, you should write it without using self. Like name1. Also, if you always want to process with the value specified in the class, you should call it as self.__ class __. name. Another advantage of writing like name1 is that it can be returned to the initial value.

name


class foo:
    name1 = 'test1'
    def __init__(self):
        self.name2 = 'test2'

bar = foo()
print(bar.name1)
# => test1
bar.name1 = 'newname'
print(bar.name1)
# => newname
del bar.name1
print(bar.name1)
# => test1

You may declare self.name only if you expect it to change or if you don't need to remember the value before the change.

Recommended Posts

[python] Difference between variables and self. Variables in class
Difference between list () and [] in Python
Difference between == and is in python
Difference between Ruby and Python in terms of variables
difference between statements (statements) and expressions (expressions) in Python
Difference between @classmethod and @staticmethod in Python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
Reference order of class variables and instance variables in "self. Class variables" in Python
[Python] Difference between class method and static method
About the difference between "==" and "is" in python
Python class variables and instance variables
Difference between return, return None, and no return description in Python
Difference between java and python (memo)
Landmines hidden in Python class variables
Difference between python2 series and python3 series dict.keys ()
[Python] Difference between function and method
Python --Difference between exec and eval
[Python] Difference between randrange () and randint ()
[Python] Difference between sorted and sorted (Colaboratory)
Python module num2words Difference in behavior between English and Russian
List concatenation method in python, difference between list.extend () and β€œ+” operator
Differences between Ruby and Python in scope
Differences in syntax between Python and Java
Difference between PHP and Python finally and exit
[Python Iroha] Difference between List and Tuple
[python] Difference between rand and randn output
Differences in multithreading between Python and Jython
Difference in how to write if statement between ruby ​​and python
Transcendental simple and clear! !! Difference between single quotes and double quotes in Python
I was addicted to confusing class variables and instance variables in Python
File open function in Python3 (difference between open and codecs.open and speed comparison)
case class in python
Python variables and data types learned in chemoinformatics
I wrote a class in Python3 and Java
Practice applying functions and global variables in Python
Trouble with Python pseudo-private variables and class inheritance
Class notation in Python
Difference in writing method to read external source code between Ruby and Python
[python] Calculation of months and years of difference in datetime
Mutual conversion between JSON and YAML / TOML in Python
Compare "relationship between log and infinity" in Gauche (0.9.4) and Python (3.5.1)
Sample of getting module name and class name in Python
Difference between "categorical_crossentropy" and "sparse_categorical_crossentropy"
Find the difference in Python
Difference between regression and classification
Handle environment variables in Python
Stack and Queue in Python
Python variables and object IDs
Difference between np.array and np.arange
Difference between MicroPython and CPython
Unittest and CI in Python
Difference between ps a and ps -a
Difference between return and print-Python
[Python] Explain the difference between strftime and strptime in the datetime module with an example
Install OpenCV 3 (core + contrib) in Windows & Python 3 environment & Difference between OpenCV 2 and OpenCV 3 & Easy operation check
Understand the difference between cumulative assignment to variables and cumulative assignment to objects
[Python] How to play with class variables with decorator and metaclass
Display numbers and letters assigned to variables in python print
I created a class in Python and tried duck typing
Get the current date and time in Python, considering the time difference