0

I am building a python class in which I create a dictionnary using the method "new". Then, I would like to define a method to affect a unit for some of the keys. Below an example of the code:

class MyClass(object):
  def __new__(cls):
    dict = {key1:None, key2:None}
    return dict

  def unit(self, unit):
    self[KEY].unit = unit

Where, in the unit method, KEY should take any key of the dictionnary. Could you please help me to understand how to code it?

In advance thank you,

3
  • 1
    Most probably you want to have an init function. Commented May 2, 2018 at 13:18
  • 1
    What exactly is the problem you are trying to solve? Commented May 2, 2018 at 13:18
  • Do not use the __new__ method. It's almost always a mistake and is definitely so in your example. You should be subclassing dict. It is also not clear where or how the magic KEY var is defined. I recommend you rephrase your question in terms of your goals rather than in terms of getting your example to work using the __new__() method. Commented May 3, 2018 at 3:09

1 Answer 1

1

I'm not sure, why you want to use __new__ instead of __init__, but you can simply iterate through all keys in the dictionary by doing:

class dictionary_setter:
  some_dic = {'key1':1, 'some_other_key':2, 'just another key':3}

def __init__(self,keys):
  self.some_dic = {}
  for k in keys:
    self.some_dic[k]='some_value'

a_test_dic = dictionary_setter(['key1','key2'])
print(a_test_dic.some_dick['key1'])

Turning a string into a variable is another topic, but you can simply refer to the dictionary entry via dot syntax.

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

5 Comments

I can not return a dictionary with init. And I would like to do something like: ` from MyClass import * dict = MyClass() dict["key1"].unit = "m/s" `
You don't have to. You can simply refer to the dictionary. Are you coming from C/Java over to python?
From fortran to python
I updated the example to show, how you can append a dictionary to the instance of a class.
I agree with that, but I still cannot affect an attirbute UNIT to "some_dic" using only the key. Cf. def unit(self, unit): self.some_dic[key].unit = unit

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.