Created
May 16, 2013 12:21
-
-
Save borntyping/5591339 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PositiveInt(object): | |
__slots__ = 'value' | |
def __init__(self, value): | |
self.__set__(instance=None, value=value) | |
def __get__(self, instance, owner): | |
return self.value | |
def __set__(self, instance, value): | |
if not value > 0 or not isinstance(value, int): | |
raise ValueError("Not a positive integer") | |
self.value = value | |
class Object(object): | |
number = PositiveInt(1) | |
myobject = Object() | |
myobject.number = 5 | |
try: | |
myobject.number = -1 | |
except ValueError: | |
pass | |
class TypeSafeAttribute(object): | |
def __init__(self, type, value): | |
self.type = type | |
self.__set__(instance=None, value=value) | |
def __get__(self, instance, owner): | |
return self.value | |
def __set__(self, instance, value): | |
if not isinstance(value, self.type): | |
raise ValueError("{value} is not an instance of {type}".format( | |
value=value, type=self.type)) | |
self.value = value | |
class Object(object): | |
attribute = TypeSafeAttribute(int, 0) | |
myobject = Object() | |
myobject.attribute = 5 | |
myobject.attribute = "hello" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment