Created
November 14, 2012 01:51
-
-
Save cjerdonek/4069742 to your computer and use it in GitHub Desktop.
A __getattr__ example.
This file contains hidden or 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
""" | |
An example of decorating a built-in type with another object. | |
Attributes and methods on the built-in type delegate to the other object. | |
""" | |
class WrappedInt(int): | |
""" | |
An integer wrapper that decorates an integer with a set. | |
""" | |
def __new__(cls, integer, elements): | |
return int.__new__(cls, integer) | |
def __init__(self, integer, elements): | |
int.__init__(self, integer) | |
self._set = set(elements) | |
def __len__(self): | |
return len(self._set) | |
def __getattr__(self, attr): | |
return getattr(self._set, attr) | |
a = WrappedInt(10, [1, 2, 3]) | |
print(a + 20) # prints 30 | |
print(len(a)) # prints 3 | |
print(a.union([4, 5, 6])) # prints set([1, 2, 3, 4, 5, 6]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment