Extending a Property in a Subclass
Problem
Within a subclass, you want to extend the functionality of a property defined in a parent class.
Solution
Consider the following code, which defines a property:
class
Person
(
object
):
def
__init__
(
self
,
name
):
self
.
name
=
name
# Getter function
@property
def
name
(
self
):
return
self
.
_name
# Setter function
@name
.
setter
def
name
(
self
,
value
):
if
not
isinstance
(
value
,
str
):
raise
TypeError
(
'Expected a string'
)
self
.
_name
=
value
# Deleter function
@name
.
deleter
def
name
(
self
):
raise
AttributeError
(
"Can't delete attribute"
)
Here is an example of a class that inherits from Person
and
extends the name
property with new functionality:
class
SubPerson
(
Person
):
@property
def
name
(
self
):
(
'Getting name'
)
return
super
()
.
name
@name
.
setter
def
name
(
self
,
value
):
(
'Setting name to'
,
value
)
super
(
SubPerson
,
SubPerson
)
.
name
.
__set__
(
self
,
value
)
@name
.
deleter
def
name
(
self
):
(
'Deleting name'
)
super
(
SubPerson
,
SubPerson
)
.
name
.
__delete__
(
self
)
Here is an example of the new class in use:
>>>
s
=
SubPerson
(
'Guido'
)
Setting name to Guido
>>>
s
.
name
Getting name
'Guido'
>>>
s
.
name
=
'Larry'
Setting name to Larry
>>>
s
.
name
=
42
Traceback (most recent call last):
File"<stdin>"
, line1
, in<module>
File"example.py"
, line16
, inname
raise
TypeError
(
'Expected ...
Get Extending a Property in a Subclass 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.