0
import json

class Myclass():

    def __init__(self):

        with open("file_name.json", "r") as read_file:
            data = json.load(read_file)

        for key in data:
            print key
            key = getattr(self,'func_name')

    def func_name(self,arg):
        print "Pass"

obj = Myclass()
obj.func_name("test")
obj.key_from_file("test")

Output:

key_from_file
Pass
Traceback (most recent call last):
  File "get_at.py", line 22, in <module>
    obj.key_from_file("test")
AttributeError: Myclass instance has no attribute 'key_from_file'

I want to dynamically map all key in json file to func_name, so whenever we call obj.key_from_file("test") which should call obj.func_name("test")

How to do that ?

Neha
  • 13
  • 1
  • 2
    I don't get the question. At all. Why would you expect `obj` to have a `key_from_file` method even though you never defined one? And what's the point of the `func_name` method? – Aran-Fey Jun 12 '18 at 11:52
  • 1
    Duplicate: https://stackoverflow.com/questions/285061/how-do-you-programmatically-set-an-attribute – Aran-Fey Jun 12 '18 at 12:05
  • Possible duplicate of [How do you programmatically set an attribute?](https://stackoverflow.com/questions/285061/how-do-you-programmatically-set-an-attribute) – Netwave Jun 12 '18 at 12:19

1 Answers1

0

Use setAttr for setting the attribute in the object:

import json

class Myclass():

    def __init__(self):
        with open("file_name.json", "r") as read_file:
            data = json.load(read_file)
        for key in data:
            print key
            setattr(self, key, self.func_name) #we create an attr with the key as name and the funct_name function as value.

    def func_name(self,arg):
        print "Pass"

obj = Myclass()
obj.func_name("test")
obj.key_from_file("test")

Here you have a live example

Netwave
  • 40,134
  • 6
  • 50
  • 93