Skip to content

Instantly share code, notes, and snippets.

@eclecticmiraclecat
Created May 31, 2020 14:03
Show Gist options
  • Save eclecticmiraclecat/3549774d093752adaeedf40e33433853 to your computer and use it in GitHub Desktop.
Save eclecticmiraclecat/3549774d093752adaeedf40e33433853 to your computer and use it in GitHub Desktop.
>>> class Integer:
... def __init__(self, name):
... self.name = name
... def __get__(self, instance, cls):
... return instance.__dict__[self.name]
... def __set__(self, instance, value):
... if not isinstance(value, int):
... raise TypeError('Expected int')
... instance.__dict__[self.name] = value
...
>>>
>>> class Point:
... x = Integer('x')
... def __init__(self, x):
... self.x = x
...
>>> p = Point(2)
>>> p.x
2
>>> p.x = 1.2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in __set__
TypeError: Expected int
>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment