Static variables in Python that are shared across files

前端 未结 1 719
执笔经年
执笔经年 2021-01-21 12:26

I am pretty new to Python and I could\'t find a way to have static variables that are shared across different python files... In Java, it seems quite straight forward to do so..

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-21 12:44

    The problem is that (I suppose) you are launching separately user1.py and user2.py. So static values of class Shared are not preserved across different invocations.

    But that's otherwise a perfectly correct way of sharing data : you declare classes or even variable in one file that is imported in the others.

    But Python is not Java, and everything does not need to be a class. You could do :

    • data.py

      list_vars = []
      var = ""
      
      def print_vars():
          print "list_vars = " + str(Shared.list_vars)
          print "var = " + Shared.var
      
    • user1.py

      import time
      import data as shared
      
      shared.list_vars.append("001")
      time.sleep(5.0)
      shared.print_vars()
      
      # It prints:
      # list_vars = ['001']
      # var =
      
    • user2.py

      import time
      import data as shared
      
      shared.var = "002"
      time.sleep(5.0)
      shared.print_vars()
      
      # It prints:
      # list_vars = []
      # var = 002
      
    • main.py

      import user1
      # It prints:
      # list_vars = ['001']
      # var =
      import user2
      # It prints:
      # list_vars = ['001']
      # var = 002
      

    0 讨论(0)
提交回复
热议问题