I am studying descriptor. They work with class varibles out of the box, but I want them to operate on instance variables too, so I did this;
class NumberDescriptor(object):
def __init__(self,name):
self.name = name
def __set__(self, instance, value):
if not isinstance(value, int):
raise ValueError("%s is not a number." % value)
else:
setattr(instance, self.name, value)
def __get__(self, instance, owner):
return getattr(instance, self.name)
class Human(object):
age = NumberDescriptor("_age")
def __init__(self,age):
self.age = age
a = Human(12)
print a.age
b = Human("osman")
print b.age
Is this right way to go about this?