Reference order of class variables and instance variables in "self. Class variables" in Python

Intro

When explaining the concept of class variables and instance variables in Python For variables that are defined as class variables but not as instance variables, Isn't it strange that you can access with the notation of instance variables self. Class variable name? I noticed. → I wrote a simple code and confirmed the behavior of self. Class variable.

What i found

In Python, when you refer to self.variable name,

  1. First, refer to the instance variable and
  2. ** If the instance variable is not defined, refer to the class variable with the same name before returning an error. ** **

To avoid congestion, it is safer to write class name.class variable name when referencing a class variable in an instance.

Sample code

self.py


class Hoge:
    id = 0

    @classmethod
    def dump_class(cls):
        print("Class variables: ", cls.id)

    def construct(self, id):
        self.id = id

    def dump_instance(self):
        print("Instance variables: ", self.id)


if __name__ == "__main__":
    Hoge.dump_class()  # -> 0

    hoge_instance = Hoge()
    hoge_instance.dump_instance()  # -> 0,If no instance variable is defined, the class variable with the same name will be referenced.
    hoge_instance.dump_class()  # -> 0

    hoge_instance.construct(id=10)  #Define instance variables
    hoge_instance.dump_instance()  # -> 10,Instance variable reference takes precedence
    hoge_instance.dump_class()  # -> 0

reference

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. Python class variables and instance variables | UX MILK

Recommended Posts

Reference order of class variables and instance variables in "self. Class variables" in Python
Python: Class and instance variables
[python] Difference between variables and self. Variables in class
Python class variables and instance variables
I was addicted to confusing class variables and instance variables in Python
Globalization of class instance variables
Difference between Ruby and Python in terms of variables
Sample of getting module name and class name in Python
Landmines hidden in Python class variables
Python class definitions and instance handling
Reputation of Python books and reference books
Create an instance of a predefined class from a string in Python
Example of using class variables and class methods
To reference environment variables in Python in Blender
[python] Get a list of instance variables
Project Euler # 1 "Multiples of 3 and 5" in Python
[Python] class, instance
Python class, instance
Python variables and data types learned in chemoinformatics
[Python] Chapter 02-01 Basics of Python programs (operations and variables)
Practice applying functions and global variables in Python
Trouble with Python pseudo-private variables and class inheritance
Explanation of edit distance and implementation in Python
[Python] Class type and usage of datetime module
About Class and Instance
case class in python
Class notation in Python
Natural order in python
Full-width and half-width processing of CSV data in Python
Calculation of standard deviation and correlation coefficient in Python
[python] Calculation of months and years of difference in datetime
[Python] How to sort dict in list and instance in list
Overview of generalized linear models and implementation in Python
Why is the first argument of [Python] Class self?
Summary of date processing in Python (datetime and dateutil)
How to achieve access by attribute and retention of insertion order in Python dict
I compared the speed of the reference of the python in list and the reference of the dictionary comprehension made from the in list.
I'm having trouble with instance variables being inherited in Python
About Python variables and objects
Applied practice of try/except and dictionary editing and retrieval in Python
How to create an instance of a particular class from dict using __new__ () in python
[Python] How to play with class variables with decorator and metaclass
Equivalence of objects in Python
Display numbers and letters assigned to variables in python print
Comparison of how to use higher-order functions in Python 2 and 3
Stack and Queue in Python
I created a class in Python and tried duck typing
[Python] Strengths and weaknesses of DataFrame in terms of time required
Python variables and object IDs
[Tips] Problems and solutions in the development of python + kivy
Unittest and CI in Python
Implementation of quicksort in Python
What beginners learned from the basics of variables in python
Source installation and installation of Python
Python # About reference and copy
I want to clear up the question of the "__init__" method and the "self" argument of a Python class.
Count the number of Thai and Arabic characters well in Python
Create your own graph structure class and its drawing in python
[python] Get the rank of the values in List in ascending / descending order
List of Linear Programming (LP) solvers and modelers available in Python
I thought a Python class variable was an instance variable and died