0
votes

I'm trying to create a class based on the dictionary. All the values in the dictionary have notation e.g. 'key1.key2.key3' where key1, key2 are parents in the dictionary tree, and key3 is the current key. So the value of key3 is a string 'key1.key2.key3'. This is to make sure that I can change the name of e.g. key2 in only one location.

The naive code for that would be:

class Key1:

    class Key2:
        KEY3 = 'key1.key2.key3'
        KEY4 = 'key1.key2.key4'

Now I can access path 'key1.key2.key3' by calling Key1.Key2.KEY3

But if I want to change 'key1' to some other name, I need to change 'key1' if many values.

I've tried to make some attributes for the classes:

class Key1:
   name = 'key1'

   class Key2:
      name = Key1.name + '.key2'
      KEY3 = Key2.name + '.key3'
      KEY4 = Key2.name + '.key4'

Python says name 'Key1' is not defined.

1
By the time Key2 is being defined Key1 is not defined yet. Also, Key2 is also not defined yet, so you can't access Key1 nor Key2. You'll have to think about another design - DeepSpace
Can't you make Key2 a child of Key1 instead ? class Key2(Key1) (same indent level) and it should work - Plopp
If I make it a child, upon developing I will loose the path as Key1.Key2.KEY3 which is important, because it shows the actual tree instead of just the end value. - siadajpan

1 Answers

0
votes
class Key1:
   def __init__(self):
       self.name = 'key1'

   class Key2:
      def __init__(self):
          self.key1 = Key1()

      def disp(self):
          name = self.key1.name + '.key2'
          print(name) # Prints as key1.key2


one_key = Key1()
one_key.Key2().disp()