Python getters and setters

Tim Chase python.list at tim.thechases.com
Sat Aug 17 13:31:01 EDT 2013


On 2013-08-17 17:18, Steven D'Aprano wrote:
> # Yes, this is good, consistent design
> len(myrecord.field)
> len(obj.data)
> len(data.value)
> len(collection[key])

I would also add that, if the primary goal of your class is to
encapsulate the data, you can do

  class MyClass:
    def __init__(self, ...):
      self.data = []
    def __len__(self):
      return len(self.data)

which allows for the even clearer

  my_obj = MyClass(...)
  manipulate(my_obj)
  if len(my_obj) > 42:
    do_important_stuff()

-tkc





More information about the Python-list mailing list