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.