Creating a New Kind of Class or Instance Attribute
Problem
You want to create a new kind of instance attribute type with some extra functionality, such as type checking.
Solution
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 attribute
class
Integer
(
object
):
def
__init__
(
self
,
name
):
self
.
name
=
name
def
__get__
(
self
,
instance
,
cls
):
if
instance
is
None
:
return
self
else
:
return
instance
.
__dict__
[
self
.
name
]
def
__set__
(
self
,
instance
,
value
):
if
not
isinstance
(
value
,
int
):
raise
TypeError
(
'Expected an int'
)
instance
.
__dict__
[
self
.
name
]
=
value
def
__delete__
(
self
,
instance
):
del
instance
.
__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:
class
Point
(
object
):
x
=
Integer
(
'x'
)
y
=
Integer
(
'y'
)
def
__init__
(
self
,
x
,
y
):
self
.
x
=
x
self
.
y
=
y
When you do this, all ...
Get Creating a New Kind of Class or Instance Attribute now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.