Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and why might I assign an instance of a descriptor class to a class attribute in Python rather than use a property?

I'm aware that a property is a descriptor, but are there specific examples of when using a descriptor class might be more advantageous, pythonic, or provide some benefit over using @property on a method function?

like image 942
mkelley33 Avatar asked Apr 30 '11 15:04

mkelley33


People also ask

What is the use of descriptor in Python?

Python descriptors are a way to create managed attributes. Among their many advantages, managed attributes are used to protect an attribute from changes or to automatically update the values of a dependant attribute. Descriptors increase an understanding of Python, and improve coding skills.

What is the difference between properties and descriptors in Python?

The Cliff's Notes version: descriptors are a low-level mechanism that lets you hook into an object's attributes being accessed. Properties are a high-level application of this; that is, properties are implemented using descriptors.

Can a class attribute can be used without an instance of that class?

while you can access class attributes using an instance it's not safe to do so. In python, the instance of a class is referred to by the keyword self. Using this keyword you can access not only all instance attributes but also the class attributes.

What is the difference between class attributes and instance attributes in Python?

Class attributes are the variables defined directly in the class that are shared by all objects of the class. Instance attributes are attributes or properties attached to an instance of a class. Instance attributes are defined in the constructor.


1 Answers

Better encapsulation and re-usability: A descriptor class can have custom attributes set on instantiating. Sometimes it's useful to keep data confined in this manner, instead of having to worry about it getting set or overwritten on the descriptor's owner.

like image 68
XORcist Avatar answered Oct 04 '22 20:10

XORcist