0

What is the difference between using the @property decorator as a "getter" and just defining the variable normally?

See an example below:


Class MyClass(object):
   def __init__(self, ....):
      ....


   @property
   def headers(self):
      return {"Content-Type": "application/json"}

Versus:

Class MyClass(object):
   def __init__(self, ....):
      .....

   self.headers = {"Content-Type": "application/json"}

Why use one over the other? When should the property decorator be used?

the man
  • 1,131
  • 1
  • 8
  • 19
  • 1
    Property is a pythonic implementation of *getters* and *setters* which is part of OOP. – Olvin Roght Aug 13 '20 at 19:51
  • a very thorough explanation of decorators: https://stackoverflow.com/questions/739654/how-to-make-a-chain-of-function-decorators/1594484#1594484 – dh762 Aug 13 '20 at 19:51
  • To elaborate on @OlvinRoght answer a bit, you can add some custom logic when getting/setting a property, which is not possible in case of class variables. – Marek Piotrowski Aug 13 '20 at 19:53
  • The beauty of the `property` class is that you can start with a publicly exposed attribute, and if you decide *later* that it should be protected by a getter and/or setter, you can do so without changing the *interface*. – chepner Aug 13 '20 at 19:54
  • @chepner So I'd use the ```property``` decorator when I wanted to keep the attribute private/unmodifiable? – the man Aug 13 '20 at 19:55
  • 1
    Yes, that's one reason to create a property without a setter. – chepner Aug 13 '20 at 19:56
  • related: https://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters – FObersteiner Aug 13 '20 at 20:01

0 Answers0