Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@seenaburns
Last active December 11, 2015 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seenaburns/4522888 to your computer and use it in GitHub Desktop.
Save seenaburns/4522888 to your computer and use it in GitHub Desktop.
Overriding __getattr__ for the sake of API Design
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