when will the python __call__ would be called? -


i tried understand following code.

class chain(object):      def __init__(self, path=''):         self._path = path      def __getattr__(self, path):         return chain('%s/%s' % (self._path, path))      def __str__(self):         return self._path      __repr__ = __str__      def __call__(self, path):         return chain('%s/%s' % (self._path, path))   print (chain().abc.efg("string").repos) 

the output is:

/abc/efg/string/repos 

what don't understand why __call__ method not called in chain(/abc) , called in chain(/abc/efg)

__getattr__ used attribute lookup on class instance. __call__ used when class instance used function.

chain()                          # creates class instance chain().abc                      # calls __getattr__ returns new instance chain().abc.efg                  # calls __getattr__ returns new instance chain().abc.efg("string")        # calls __call__ 

__getattr__ can handle strings python recognizes valid variable names. __call__ useful when non-conforming string wanted. so, instance, chain().abc.def("some string spaces") example.


Comments