I thought a Python class variable was an instance variable and died

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.

Conclusion

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 ...

Style to step through with full power

** 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 ...

Summary

Let's stop python in the atmosphere

Recommended Posts

I thought a Python class variable was an instance variable and died
I wrote a class in Python3 and Java
Python: Class and instance variables
Python class variables and instance variables
Python: I tried a liar and an honest tribe
Python class definitions and instance handling
[Python] class, instance
Python class, instance
Python: Prepare a serializer for the class instance:
python memo-"if not A and B" was "if (not A) and B"
About Class and Instance
I want to embed a variable in a Python string
I made a LINE BOT with Python and Heroku
Don't take an instance of a Python exception class directly as an argument to the exception class!
A story that I wondered if it stopped working at mglearn.plots.plot_nmf_faces and was an error?
How to create an instance of a particular class from dict using __new__ () in python
I was surprised to receive a nice review when I wrote Python to CheckIO and its explanation
I thought about a Python beginner's course on blockchain games
I got an error in vim and zsh in Python 3.7 series
Consider If Programming Was An Anime in Python and C
Reference order of class variables and instance variables in "self. Class variables" in Python
I made a Chatbot using LINE Messaging API and Python
What is an instance variable?
I made a python text
I wrote AWS Lambda, and I was a little addicted to the default value of Python arguments
I want to clear up the question of the "__init__" method and the "self" argument of a Python class.
I made a simple circuit with Python (AND, OR, NOR, etc.)
[Python3] I made a decorator that declares undefined functions and methods.
[Road to Python Intermediate] Call a class instance like a function with __call__
I made a Nyanko tweet form with Python, Flask and Heroku
I tried to make a periodical process with Selenium and Python
Homework was a pain, so I do management accounting with Python
[Python] I wrote a REST API using AWS API Gateway and Lambda.
I made a Chatbot using LINE Messaging API and Python (2) ~ Server ~
[python] I made a class that can write a file tree quickly
I want to pass an argument to a python function and execute it from PHP on a web server
Python a + = b and a = a + b are different
How to write a Python class
I made a Line-bot using Python!
I made a fortune with Python.
I sent an SMS with Python
I made an app for foreign visitors to Japan with a hackathon and won a prize, but when I thought about it carefully, it was useless.
I played with PyQt5 and Python3
perl objects and python class part 1.
[Python] return A [or / and] B
[Python] Inherit a class with class variables
I made a daemon with Python
Python classes and instances, instance methods
About launching an instance with an encrypted EBS volume (where I was addicted)
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
Tips: [Python] Randomly restore and extract an array from a fasta file
[Python] Create a linebot to write a name and age on an image
I set the environment variable with Docker and displayed it in Python
A python program that resizes a video and turns it into an image
Hit a method of a class instance with the Python Bottle Web API
The file name was bad in Python and I was addicted to import
I want to color a part of an Excel string in Python
[Python] I was hooked for an hour trying to use list comprehensions
[Python] It was very convenient to use a Python class for a ROS program.
I want to make a web application using React and Python flask