It may be amateurish, but I don't really understand the need for the initialization method.Even if I read books, I don't feel satisfied with just the methods and variables defined in the class first.
For example, suppose you have two classes:
These two classes seem to work the same way, but what's the difference between defining variables in the initialization method and defining variables outside of the initialization method?I would appreciate it if you could let me know.
class test1:
x = 5
def func1(self):
self.x = self.x+1
print(self.x)
class test2:
def__init__(self):
self.x = 5
def func2(self):
self.x = self.x+1
print(self.x)
I'm asking if it's handled by the initialization method, but it seems to be mixed with the difference between the class variable and the instance variable.
Also, although a program like the question can be created and operated, it seems that it is actually deprecated.
The articles around here will be helpful.
Memorandum of Understanding on the Behavior of Instance and Class Variables in Python Classes
How do I access class variables?
Python class and instance variables
The article above will derive the following:
print(test1.x)
with only class definitiont1=test1()
, where t1.x
and test1.x
are separatet1.func1()
, t1.x
becomes 6
and test1.x
remains 5
t2=test2()
, you can do print(t2.x)
but not print(test2.x)
print(test1.x)
with only class definitiont1=test1()
, where t1.x
and test1.x
are separatet1.func1()
, t1.x
becomes 6
and test1.x
remains 5
t2=test2()
, you can do print(t2.x)
but not print(test2.x)
© 2025 OneMinuteCode. All rights reserved.