This recipe shows how to add a __getattr__ method to your class that allows you to use shortened forms for attribute names in interactive use.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | class Sample(object):
"""Show how to add support for abbreviated long names to an object.
>>> sample = Sample()
>>> sample.__dict__
{'x': 1, 'xylophone': 2, 'verylongname': 20}
>>> sample.x
1
>>> sample.xylophone
2
>>> sample.xy
2
>>> sample.v
20
>>> sample.z
Traceback (most recent call last):
AttributeError
"""
def __init__(self):
self.x = 1
self.xylophone = 2
self.verylongname = 20
def __getattr__(self,attr):
if attr in self.__dict__:
return self.__dict__[attr]
else:
choices = [a for a in self.__dict__ if a.startswith(attr)]
if len(choices)==1:
return self.__dict__[choices[0]]
else:
raise AttributeError
if __name__=="__main__":
import doctest,recipe
doctest.testmod(recipe)
|
Having written a parser that extracts information from a log file, I created a class to store the results using descriptive names for the attributes. In interactive use, in the absence of tab-completion, entering the complete attribute name was both painful and error-prone.
This recipe shows how to add a __getattr__ method to your class that allows you to use shortened forms for attribute names. If the attribute name matches an attribute exactly, the value of that attribute is returned. Otherwise, if it is the start of a longer attribute name, the value of the matching attribute is returned. If the abbreviation matches two or more attributes or zero attributes, an AttributeError is raised.
This __getattr__ method is particularly useful where long and descriptive attribute names may be referred to in interactive use.
The above doctest code assumes that the recipe is saved as recipe.py.