August 2024
Beginner
5 pages
4m
English
You want to create a new kind of instance attribute type with some extra functionality, such as type checking.
If you want to create an entirely new kind of instance attribute, define its functionality in the form of a descriptor class. Here is an example:
# Descriptor attribute for an integer type-checked attributeclassInteger(object):def__init__(self,name):self.name=namedef__get__(self,instance,cls):ifinstanceisNone:returnselfelse:returninstance.__dict__[self.name]def__set__(self,instance,value):ifnotisinstance(value,int):raiseTypeError('Expected an int')instance.__dict__[self.name]=valuedef__delete__(self,instance):delinstance.__dict__[self.name]
A descriptor is a class that implements the three core attribute
access operations (get, set, and delete) in the form of __get__(),
__set__(), and __delete__() special methods. These methods
work by receiving an instance as input. The underlying
dictionary of the instance is then manipulated as appropriate.
To use a descriptor, instances of the descriptor are placed into a class definition as class variables. For example:
classPoint(object):x=Integer('x')y=Integer('y')def__init__(self,x,y):self.x=xself.y=y
When you do this, all ...
Read now
Unlock full access