python - How does __call__ actually work? -


python's magic method __call__ called whenever attempt call object. cls()() equal cls.__call__(cls()).

functions first class objects in python, meaning they're callable objects (using __call__). however, __call__ function, has __call__, again has own __call__, again has own __call__.

so cls.__call__(cls()) equal cls.__call__.__call__(cls()) , again equilevant cls.__call__.__call__.__call__(cls()) , on , forth.

how infinite loop end? how __call__ execute code?

under hood, calls in python use same mechanism, , arrive @ same c function in cpython implementation. whether object instance of class __call__ method, function (itself object), or builtin object, calls (except optimized special cases) arrive @ function pyobject_call. c function gets object's type ob_type field of object's pyobject struct, , type (another pyobject struct) gets tp_call field, function pointer. if tp_call not null, calls through that, args , kwargs structures passed pyobject_call.

when class defines __call__ method, sets tp_call field appropriately.

here's article explaining of in detail: python internals: how callables work. lists , explains entire pyobject_call function, isn't big. if want see function in native habitat, it's in objects/abstract.c in cpython repo.

also relevant stackoverflow q&a: what "callable" in python?.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -