[Tutor] I can't understand where python class methods come from
James Scholes
james at jls-radio.com
Sun Feb 23 23:21:17 CET 2014
voger wrote:
> Some properties I can see them defined but some others like
> sublocality or administrative_area_level_1 I don't see them defined
> anywhere. Also in the comments in the source code the author says
>
> #You can also choose a different property to display for each lookup
> #type. # Example: # result.country__short_name
>
> but I can't understand where that __short_name comes from
The relevant code is in the __getattr__ method. From the Python docs:
> If no class attribute is found, and the objects class has a
> __getattr__() method, that is called to satisfy the lookup.
>
> -- Source:
> http://docs.python.org/2/reference/datamodel.html
As an aside, your examples are attributes, not methods. Read the code
below; this is where the magic happens:
def __getattr__(self, name):
lookup = name.split('__')
attribute = lookup[0]
if (attribute in GeocoderResult.attribute_mapping):
attribute = GeocoderResult.attribute_mapping[attribute]
try:
prop = lookup[1]
except IndexError:
prop = 'long_name'
for elem in self.current_data['address_components']:
if attribute in elem['types']:
return elem[prop]
--
James Scholes
http://twitter.com/JamesScholes
More information about the Tutor
mailing list