API design question: use methods or properties? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: API design question: use methods or properties? (/thread-30215.html) |
API design question: use methods or properties? - johsmi96 - Oct-12-2020 This is something that is really bugging me, but I cannot come up with a good strategy for how to decide: should I use ordinary methods or properties (via the property decorator) to access information about my objects? For example: obj1 = MyClass() obj1.size # get the sizeobj1.starttime # get the start timeor rather stick with obj1.size() # get the sizeobj1.starttime() # get the start timeAll these are retrieving information from the object/about the object which cannot be assigned by the user so this should not be allowed/possible: obj1.size = 22 # throws exceptionI started using properties for the most obvious cases but then realized that quite a number of methods could get turned into properties like that and I ended up with so many that it did not feel right. Taken to the extreme, one could just replace all methods which do not have any parameters and never will have with a property especially if those methods will also never be used to get passed around as a function reference. How do others approach this design dilemma? RE: API design question: use methods or properties? - buran - Oct-12-2020 use @property decorator class Foo: @property def size(self): return 42 foo = Foo() print(foo.size) foo.size = 32output 42 Traceback (most recent call last): File "/home/boyan/sandbox2/forum.py", line 34, in <module> foo.size = 32 AttributeError: can't set attribute |