What is the difference between attributes and properties in Python?

Python Methods and Functions

In python, everything is an object. And every object has attributes and methods or functions. Attributes are described by data variables such as name, age, height, etc.

Properties &they are a special kind of attributes that getter, setter, and delete methods have, such as __get__, __set__, and __delete__. 

However, Python has a property decorator that provides getter / setter access to an attribute. Properties &it is a special kind of attribute. Basically when Python comes across the following code:





 foo = SomeObject () print (foo.bar) 

it looks at bar in foo, and then checks bar to see if there is a __get__, __set__, or __delete__ method, and if so, then that is a property. If it's a property, and not just returning a bar object, it will call the __get__ method and return whatever that method returns.

In Python, you can define getter, setter, and delete methods using a property function. If you just need a read property, there is also an @property decorator that you can add above your method.

 class C (object): def __init __ (self): self._x = None # C._x is an attribute @property def x (self): "" "I'm the' x' property. "" " return self._x # C._x is a property This is the getter method @ x.setter # This is the setter method def x (self, value): self._x = value @ x.deleter # This is the delete method def x (self): del self._x 







Get Solution for free from DataCamp guru