>>> class _TypedAttribute(object):
... def __init__(self, name, typ):
... self.typ = typ
... def __set__(self, inst, val):
... if isinstance(val, self.typ):
... else:
... raise TypeError
...
>>> class TypedAttribute(object):
... def __init__(self, typ):
... self.typ = typ
...
>>> class TypedClass(type):
... def __new__(cls, name, bases, attrs):
... for k, v in attrs.items():
... if isinstance(v, TypedAttribute):
... attrs[k] = _TypedAttribute(k, v.typ)
... return type.__new__(cls, name, bases, attrs)
...
>>> class Person(object):
... __metaclass__ = TypedClass
... name = TypedAttribute(str)
... age = TypedAttribute(int)
...
>>> p = Person()
'Bill'
>>> p.age = 25
>>> p.age
25
>>> p.age = '25'
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "<console>", line 9, in __set__
TypeError
>>> p.age
25