I was addicted to confusing class variables and instance variables in Python

I confused a class variable with an instance variable in Python, so it didn't work as I expected. Make a note for reference.

Overview

It seems to be a common mistake, and there are articles dealing with the same topic.

The points are summarized in this comment.

The behavior of python is that when referring to self.odds, it first refers to the instance variable, otherwise it refers to the class variable.

Another article also calls attention.

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.

Let's see this with a simple example.

Pit

Since I can access class variables via self, I misunderstood that I defined an instance variable.

class Test:
    a = []

    def append(self, value):
        self.a.append(value)

    def clear(self):
        self.a = []

t1 = Test()
t1.append(123)
print(t1.a)

t1.clear()
print(t1.a)

Execution result


[123]
[]

Looking at this, I thought that the value was cleared. In reality, the class variable is just obscured by the instance variable of the same name.

If you create another instance, you will see the class variable with 123 added.

t2 = Test()
print(t2.a)

Execution result


[123]

What I really fell in love with was a program that called clear many times. Although I noticed that the behavior was strange, I did not pay attention to the state immediately after the instance was created, and the investigation of the cause was delayed.

Countermeasures

Let's initialize the instance variable with the constructor.

class Test:
    def __init__(self):
        self.a = []

Recommended Posts

I was addicted to confusing class variables and instance variables in Python
Python: Class and instance variables
Python class variables and instance variables
The file name was bad in Python and I was addicted to import
I was addicted to scraping with Selenium (+ Python) in 2020
Reference order of class variables and instance variables in "self. Class variables" in Python
What I was addicted to when combining class inheritance and Joint Table Inheritance in SQLAlchemy
What I was addicted to Python autorun
What I was addicted to with json.dumps in Python base64 encoding
I thought a Python class variable was an instance variable and died
I was able to recurse in Python: lambda
[python] Difference between variables and self. Variables in class
I wrote a class in Python3 and Java
[Python] I was addicted to not saving internal variables of lambda expressions
Three things I was addicted to when using Python and MySQL with Docker
[Python] How to sort dict in list and instance in list
I was able to repeat it in Python: lambda
I was addicted to trying logging.getLogger in Flask 1.1.x
What I was addicted to when using Python tornado
I was soberly addicted to calling awscli from a Python 2.7 script registered in crontab
I want to replace the variables in the python template file and mass-produce it in another file.
[Python] How to play with class variables with decorator and metaclass
Display numbers and letters assigned to variables in python print
What I was addicted to when migrating Processing users to Python
[Fixed] I was addicted to alphanumeric judgment of Python strings
Landmines hidden in Python class variables
Python class definitions and instance handling
I was addicted to multiprocessing + psycopg2
When I tried to install PIL and matplotlib in a virtualenv environment, I was addicted to it.
I want to solve APG4b with Python (only 4.01 and 4.04 in Chapter 4)
What I was addicted to when introducing ALE to Vim for Python
I tried to implement PLSA in Python
When I tried to scrape using requests in python, I was addicted to SSLError, so a workaround memo
How to access environment variables in Python
I wrote AWS Lambda, and I was a little addicted to the default value of Python arguments
I tried to implement permutation in Python
How to dynamically define variables in Python
I tried to implement PLSA in Python 2
I was addicted to Flask on dotCloud
I tried to implement ADALINE in Python
To reference environment variables in Python in Blender
I wanted to solve ABC159 in Python
I tried to implement PPO in Python
How to use __slots__ in Python class
How to use is and == in Python
A story I was addicted to when inserting from Python to a PostgreSQL table
I was addicted to creating a Python venv environment with VS Code
I want to explain the abstract class (ABCmeta) of Python in detail.
[Python] class, instance
Numpy's intellisense (input completion) is incomplete in VS Code and I was lightly addicted to the solution
Python class, instance
I want to do Dunnett's test in Python
Python variables and data types learned in chemoinformatics
[Introduction to json] No, I was addicted to it. .. .. ♬
I want to create a window in Python
I wrote "Introduction to Effect Verification" in Python
Send messages to Skype and Chatwork in Python
I want to merge nested dicts in Python
Practice applying functions and global variables in Python
Trouble with Python pseudo-private variables and class inheritance
I tried to implement TOPIC MODEL in Python