Skip to main content

Getter and Setter Pattern

Getters and setters are evil. Evil, evil, I say! Python objects are not Java beans. Do not write getters and setters. This is what the ‘property’ built-in is for. And do not take that to mean that you should write getters and setters, and then wrap them in ‘property’. That means that until you prove that you need anything more than a simple attribute access, don’t write getters and setters. They are a waste of CPU time, but more important, they are a waste of programmer time. Not just for the people writing the code and tests, but for the people who have to read and understand them as well.

  • Class Attributes... 
    • are variables where you can access through the instance, class, or both. 
    • holds an internal state.  
    • Two ways to access class attributes:
      1. Directly (breaks encapsulation) 
        • If accessed directly, they become part of Public API
        • Only use if sure that no behavior (methods) will ever be attached to the variables  (@dataclass?)
        • Changing implementation will be problematic:
          • Converting stored attribute -> computed attribute. Want to be able to store attributes instead of recomputing each time 
        • No internal implementation 
      2. Methods (ideal) 
        • Two methods to respect encapsulation
          • Getter: Allows Access
          • Setter: Allows Setting or Mutation 
  • Implementation
    • Making attributes Non-public
      • use underscore in variable name ( _name ) 
    • Writing Getter and Setter Methods for each attribute
      • In a class, __init__ is the attributes (variables)