将值分配给文件外部的静态属性

时间:2017-01-21 22:03:16

标签: python

以下assign.py应将值正确发送到class1.py。但是,打印返回0.0。我将dict作为静态,因此我可以从外部文件分配给它。我错过了什么吗?

class1.py

class Class1():
   dict = {}

   def set_dictionary(x,y,z):
       if (x, y) not in Class.dict:
          Class1.dict[(x, y)] = 0.0
       Class1.dict[(x,y)] = z
       print ("(%s --> %s) = %s" % (x,y,z))

assign.py

import class1 as cnt

cnt.Class1.set_dictionary('s1','s2', 100)

1 个答案:

答案 0 :(得分:1)

正如评论中所建议的那样,classmethod是可行的方法:

# class1.py
class Class1(object):
  dic = {}  # don't shadow built-ins

  @classmethod
  def set_dictionary(cls, x, y, z):
    cls.dic[(x,y)] = z
    print ("(%s --> %s) = %s" % (x, y, z))

# assign.py
import class1 as cnt
cnt.Class1.set_dictionary('s1','s2', 100)

>>> Class1.set_dictionary('s1','s2', 100)
(s1 --> s2) = 100

更多关于the different kinds of methods in Python