0

I have a class as such:

class ABC():

    def __init__(self, details):
        for key, value in self.details.items():
            setattr(self, key, value)

    def get_details(self, id):
         details = {'a':1,'b':2,'c':3}
         return self.details

I am calling the class in another file as such:

my_class = ABC(details={})
my_var = my_class.get_details('some_id')

So I have a dictionary returned from a class method, I want it's values to be assigned as class variables so that I can call them using my_class.a and so on for all the returned dictionary keys...

How can I achieve this, and is this the right approach I'm taking?

ramez
  • 321
  • 3
  • 22
  • Are you trying to do this ? https://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters – Jona Nov 27 '19 at 13:43
  • I am trying to assign dictionary values from a dictionary returned from a class function as class variables... – ramez Nov 27 '19 at 13:51
  • You should ask yourself if you need a class with dynamic attributes. If the possible number of attributes is too high, then it wouldn't be easy to maintain in the code. If the number of attributes is affordable to have each one in code, then you should define the class with all the attributes. – Ignacio Franco Nov 27 '19 at 13:51

2 Answers2

0

This will assign dictionary values to attributes:

class ABC():

    def __init__(self, details=None):
        self.set_details(details)  

    def set_details(self, details):
        if details and getattr(details, 'items', None):
            for key, value in details.items():
                setattr(self, key, value)

    def get_details(self, id):
         return getattr(self, id, None)

my_obj = ABC()
my_obj.set_details(details = {'a':1,'b':2,'c':3})
my_var = my_obj.get_details('b')
print(my_var)
print(my_obj.a)

Is this what you want ?

Jona
  • 1,218
  • 1
  • 10
  • 20
0

I don't know if I would take this approach but here is the code:

class ABC():

    def __init__(self, details=None):
        self.details = details   

    def get_details(self, ):
        details = {'a':1,'b':2,'c':3}
        self.details = details

    def set_attributes_from_details(self,):
        assert self.details, 'details not obtained yet'
        for key, value in self.details.items():
            setattr(self, key, value)

Then you can do:

a = ABC()
a.get_details()
a.set_attributes_from_details()
print(a.c)
Ignacio Franco
  • 126
  • 1
  • 8