1

I stumbled upon some Python code that implements a REST API, which acts upon (i.e. get/set) a class like this:

class Model(
    def __init__(self, foo=1, bar=0, baz=0):
        self.foo = foo
        self.bar = bar
        self.baz = baz


    def get_api(self):
        return self.__dict__.keys()


    def set_parameters(self, parameters):
        for p in parameters.keys():
            if p in self.__dict__.keys():
                self.__dict__[p] = parameters[p]

Basically the REST API is "built" from get_api(), therefore it matches 1:1 with the class' instance attributes.

Is it considered "good practice" in the Python world? (it looks a bit hack-ish to me)

If not, what would be a better way to store a model in a class?

sampei
  • 105
  • 1
  • 6

1 Answers1

0

The method used is fine, but you have some terminology errors:

self.foo, etc., are instance attributes -- that is, you'll only see them on instances of Model:

>>> Model.foo  # class access
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Model' has no attribute 'foo'

>>> m = Model()  # create an instance
>>> m.foo        # instance access
1

properties are very specific types of attributes: basically, they are bits of data backed by code (this answer has more details).

Community
  • 1
  • 1
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237