Python Forum
API design question: use methods or properties?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
API design question: use methods or properties?
#1
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 time 
or rather stick with
 
obj1.size() # get the sizeobj1.starttime() # get the start time 
All 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 exception
I 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?
Reply
#2
use @property decorator
class Foo:
    @property
    def size(self):
        return 42

foo = Foo()
print(foo.size)
foo.size = 32
output
42
Traceback (most recent call last):
  File "/home/boyan/sandbox2/forum.py", line 34, in <module>
    foo.size = 32
AttributeError: can't set attribute
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  PDF properties doesn't show created or modified date Pedroski55 4 1,007 Jun-19-2023, 08:09 AM
Last Post: Pedroski55
  How do I list properties quarinteen 0 1,038 May-01-2022, 04:15 PM
Last Post: quarinteen
  Create a 3D volume with some properties. Rosendo 0 1,384 Jul-18-2020, 08:20 PM
Last Post: Rosendo
  printing class properties from numpy.ndarrays of objects pjfarley3 2 1,909 Jun-08-2020, 05:30 AM
Last Post: pjfarley3
  adding properties to variables rudihammad 0 1,659 May-06-2020, 05:09 AM
Last Post: rudihammad
  Question about naming variables in class methods sShadowSerpent 1 1,963 Mar-25-2020, 04:51 PM
Last Post: ndc85430
  Design question will __call__ rudihammad 1 1,866 Aug-11-2019, 11:58 AM
Last Post: ichabod801
  Question on a code's design ebolisa 1 2,127 Apr-03-2019, 07:49 AM
Last Post: Gribouillis
  iterate over class properties? NobahdiAtoll 10 9,869 Aug-26-2018, 08:43 PM
Last Post: NobahdiAtoll
  Advance properties read from xml files python1234 0 2,395 Apr-25-2018, 01:42 PM
Last Post: python1234

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020