0

I have a dictionary (dict1)

dict1={
    'lala':{
            'name':'lala',
            'lula':0xcafecafe,
            },
    'mene':{
            'name':'mene',
            'lula':0xdeadbeef,
            },}

After that i created a register class to parse in the information

class register:
    def __init__(self,name):
        self.name = dict1[name].get('name')
        self.data = dict1[name].get('lula')

    def self_add(self):
        value = self.data + self.data
        print('self_add value : {}'.format(value))

and create a for loop to populate the it

for name, info in dict1.items():
    reg_class = register(name)
    vars()[reg_class.name]=reg_class ##work
    vars()['base_path'+'.'+reg_class.name]= reg_class ## not working

however, when i use vars()[reg_class.name]=reg_class it is working

>>> mene.data
3735928559
>>> hex(mene.data)
'0xdeadbeef'

but when i use vars()['base_path'+'.'+reg_class.name]= reg_class it is not working

>>> base_path.mene.data
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'base_path' is not defined

How can i do that correctly?

4
  • The correct thing to do is to create a dict of register objects, rather than injecting new names in to the local scope.
    – chepner
    Commented May 18, 2021 at 3:22
  • The reason i add this was because i would like to have some function coming with the class instead for example a sellf_add function so when we call mene.self_add it will return a value >>> mene.data 3735928559 >>> mene.self_add() self_add value : 7471857118 >>>
    – Jonathan
    Commented May 18, 2021 at 5:37
  • @Enzo what is lula?
    – LuisAFK
    Commented May 18, 2021 at 5:39
  • It's because of the dot after base_path, please modify it to vars()['base_path'+''+reg_class.name]= reg_class Use any other delimiter instead of "" but not "." because when "." is used, it considers it to be a different variable and tries to find a path inside it ( which is not there as bas_path is not defined) Commented May 18, 2021 at 7:59

0

Your Answer

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

Browse other questions tagged or ask your own question.