[Python] Variables

I tried various things with Python. I've only used statically typed languages so far, so At first I was quite confused, but I think I've become able to write something at the tool level ...

Also, I struggled with the scope of variables. Differences between other global variables, class variables, and instance variables.

test_1.py


#!/usr/bin/env python
# coding:UTF-8

#Global variables
global_var = "global"

class Test1(object):
    #Class variables
    class_var = "class"

    def __init__(self):
        #Instance variables
        self.instance_var = "instance"

Global variables are variables handled in modules (files?) While being called global. You can call only the variable name, but when you change the contents, you need to declare as below in the function

test_1.py


    def global_var_test(self):
        #Global Declaration
        global gloval_var
        #Then you can change the contents
        global_var = "change"

By the way, I don't know how to call it from another module ... Well, I don't think it's like calling from another module.

I think it's a good idea to call class variables as follows.

test_1.py


    def get_class_var(self):
        return Test1.class_var

If you use self.class_var, it will be called as a class variable when you call it, Once assigned, the instance variable will be initialized. (If it is an instance variable once, the instance variable will be called the next time it is called.)

Therefore, it is better to fix the instance name.variable name format only to the instance variable for myself later.

Recommended Posts

[Python] Variables
Python memorandum numbering variables
[Python] Get environment variables
Python
Python: Class and instance variables
About Python variables and objects
Python notes using perl-special variables
Handle environment variables in Python
# 1 [python3] Simple calculation using variables
Python class variables and instance variables
Python Beginner's Guide (Variables / Arrays)
Python variables and object IDs
kafka python
Initializing global variables using Python decorators
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python comprehension
Python technique
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
python tips
python function ①
Python basics
Python memo
ufo-> python (3)
Python comprehension
Landmines hidden in Python class variables
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Python Jinja2
Python increment
atCoder 173 Python
[Python] function
Class variables
Python installation
python tips
Try python
Python memo
Python iterative
Python2 + word2vec
Python functions
Python sys.intern ()
Python tutorial
Python decimals
python underscore
Python summary
Start python
[Python] Sort
Note: Python
Python basics ③
python log
Python basics
[Scraping] Python scraping