Last active
December 11, 2015 01:19
-
-
Save seenaburns/4522888 to your computer and use it in GitHub Desktop.
Overriding __getattr__ for the sake of API Design
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 Color: | |
def __init__(self): | |
pass | |
def __getattr__(self, name): | |
if name is 'saturation': | |
# Warn user of hls / saturation | |
saturation_warning = 'Color.saturation is ambiguous. Use Color.hls_saturation or Color.hsv_saturation' | |
raise AttributeError(saturation_warning) | |
else: | |
# Default | |
raise AttributeError | |
In action: | |
>>> c = Color() | |
>>> c.saturation | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
File "test.py", line 9, in __getattr__ | |
raise AttributeError(saturation_warning) | |
AttributeError: Color.saturation is ambiguous.Use Color.hls_saturation or Color.hsv_saturation | |
Source: | |
http://stackoverflow.com/questions/2405590/how-do-i-override-getattr-in-python-without-breaking-the-default-behavior |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment