以下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)
答案 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