Need for initialization methods in Python classes

Asked 2 years ago, Updated 2 years ago, 218 views

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)

python

2022-09-30 21:56

1 Answers

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:

  • Class variables exist and can be accessed without having to create an instance
    • You can do print(test1.x) with only class definition
  • When you create class variables and instance variables with the same name, there are separate and independent variables.
    • t1=test1(), where t1.x and test1.x are separate
    • The source of the question returns the same value when creating the instance, but after t1.func1(), t1.x becomes 6 and test1.x remains 5
  • Even if you create an instance, you cannot access it as a class variable without a class variable.
      Even if
    • t2=test2(), you can do print(t2.x) but not print(test2.x)
  • You can do print(test1.x) with only class definition
  • t1=test1(), where t1.x and test1.x are separate
  • The source of the question returns the same value when creating the instance, but after t1.func1(), t1.x becomes 6 and test1.x remains 5
    Even if
  • t2=test2(), you can do print(t2.x) but not print(test2.x)


2022-09-30 21:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.