0

The following assign.py should send the value correctly to class1.py. However, the printing return 0.0. I made dict as a static so I can assign to it from outside file. Am I missing something?

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)
3
  • 4
    You should use a classmethod. Commented Jan 21, 2017 at 22:05
  • Your code doesn't work ("Class" is not defined) but when I fix that, it runs as expected. I cannot duplicate. Commented Jan 21, 2017 at 22:08
  • What are you trying to do with this code? There is a conventional way to do object oriented programming in Python. The language lets you break those conventions. But that's usually a bad idea. In this case it's not at all clear what you expect this code to do. Commented Jan 21, 2017 at 22:09

1 Answer 1

1

As suggested in the comments, a classmethod is the way to go:

# 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

More on the different kinds of methods in Python.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.