[Edu-sig] A Descriptor (demonstrating the concept)
Kirby Urner
kurner at oreillyschool.com
Wed Mar 5 06:17:41 CET 2014
"""
Just for Fun
A quick sketch of a Descriptor construct.
A descriptor is a type instance with a
__get __ and __set__ protocol, also __delete__,
and designed to satisfy a common need to manage
setting and getting with mediating methods.
http://docs.python.org/3.4/howto/descriptor.html
(cc) Kirby Urner, MIT License
O'Reilly School of Technology
"""
class Guardian:
"""
Takes a field name and a function for screening
out banned values for said field name
"""
def __init__(self, fn, banned):
self.field = fn
self.banned = banned
def __set__(self, obj, val):
# print("Setting {} on {}".format(self.field, obj))
if self.banned(val):
raise AttributeError("Can't be {}".format(val))
obj.__dict__[self.field] = val
def __get__(self, obj, objtype):
objtype.ringding() # calls class method
return obj.__dict__[self.field]
class Guest:
# data descriptors
age = Guardian("age", banned = lambda a: a in range(1,21)) # 21 or
older
fave_color = Guardian("fave_color", banned = lambda c: c in ["Orange",
"Black"])
def __init__(self, n, age=0, fc=None):
self.name = n
# data descriptors always override instance dictionaries.
self.age = age
self.fave_color = fc
@classmethod
def ringding(cls): # called by __get__ in data descriptors
print("Ring Ding!")
def __repr__(self):
return "Guest of name {}".format(self.name)
t1 = Guest('Helga', 40)
t2 = Guest('Vlad', 30)
print("Age of t2:", t2.age)
try:
t1.age = 11 # comes up against banned()
except AttributeError:
print("No can do: 11")
try:
t1.fave_color = "Orange" # ditto banned()
except AttributeError:
print("No can do: Orange")
t1.age = 22
t1.fave_color = "Green"
# attributes stick to their respective instances if legal
print(t1.age)
print(t1.fave_color)
print(t2.age)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20140304/7cbf855b/attachment-0001.html>
More information about the Edu-sig
mailing list