简体   繁体   中英

when will the python __call__ would be called?

I tried to understand the 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 I don't understand is why the __call__ method was not called in the Chain(/abc) , but was called in the Chain(/abc/efg)

__getattr__ is used for attribute lookup on a class instance. __call__ is used when a class instance is used as a function.

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

__getattr__ can only handle strings that python recognizes as valid variable names. __call__ is useful when a non-conforming string is wanted. So, for instance, Chain().abc.def("some string with spaces") would be a good example.

abc is considered an attribute rather than a method call. Therefore it should be handled by __getattr__ instead of __call__ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM