In Python 3.6, I can use the __set_name__
hook to get the class attribute name of a descriptor. How can I achieve this in python 2.x?
This is the code which works fine in Python 3.6:
class IntField:
def __get__(self, instance, owner):
if instance is None:
return self
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, int):
raise ValueError('expecting integer')
instance.__dict__[self.name] = value
def __set_name__(self, owner, name):
self.name = name
class Example:
a = IntField()