No matter how many times I recreated the instance, the variable I intended to create with __init__ ()
did not change, and I was addicted to it for months.
I've been misunderstanding since I started writing python
class H:
val = 1 <-------this is
def __init__(self):
self.val = 1 <-------I thought it was the same as this
It was really like this
class H:
val = 1 <-------Class variables
def __init__(self):
self.val = 1 <-------Instance variables
test code
import datetime, time
#Class variables
class A:
t = datetime.datetime.today() #<-----------------#Class variable: No matter how many instances you create, it doesn't change! !!
class B:
def __new__(cls): # <----------------# __new__Instance variables
self = object.__new__(cls)
# print('__new__ :', str(id(self)))
self.t = datetime.datetime.today()
return self
class C:
def __init__(self): # <----------------# __init__Instance variables
self.t = datetime.datetime.today()
class D:
def __call__(self): # <----------------# __call__Instance variable is class name()Called by. instance.__call__()Feeling to save labor.
return datetime.datetime.today()
def start():
print("-start")
print(datetime.datetime.today())
print("-A")
instance = A()
print(A.t) #Only the class variable can be called directly from the class, not the instance
print(instance.t) #Get from instance<-----------Common value for different instances (fixed by the number when class was first called)
print("-B")
instance = B()
print(instance.t)
print("-C")
instance = C()
print(instance.t)
print("-D")
instance = D()
print(instance()) # <---------------- __call__Is the class name()Called by. instance.__call__()Feeling to save labor.
##############################################################
if __name__ == "__main__":
start()
print("=========================================")
time.sleep(1)
start()
result
I'm recreating an instance
-start
2020-01-30 14:29:24.227419
-A
2020-01-30 14:29:24.227217 <-----------here
2020-01-30 14:29:24.227217
-B
2020-01-30 14:29:24.227470
-C
2020-01-30 14:29:24.227494
-D
2020-01-30 14:29:24.227516
=========================================
-start
2020-01-30 14:29:25.230648
-A
2020-01-30 14:29:24.227217 <-----------Here is the same orz
2020-01-30 14:29:24.227217
-B
2020-01-30 14:29:25.230766
-C
2020-01-30 14:29:25.230833
-D
2020-01-30 14:29:25.230877
Others are different. The class variable was such a thing ...
** Notes on using class variables ** When accessing class variables, you should avoid accessing them like "instance.class variables" or "self.class variables" unless you have a specific reason to do so. In Python, you can create an instance variable from an instance object, and you may unintentionally hide a class variable with an instance variable. https://uxmilk.jp/41600
We are doing our best in various places. Howl ~. It was a mess ...
Let's stop python in the atmosphere
Recommended Posts