Skip to content

Is it possible to define a protocol for a method? #1040

Answered by Akuli
tobinus asked this question in Q&A
Discussion options

You must be logged in to vote

I'm starting to think that the "callback protocol" approach is not usable for this usecase, because an instance of a class with a __call__ method is not functionally equivalent to a function when assigned as a class attribute.

That's correct. When Python looks up a method from an instance, it calls __get__ to get a method object, which it then __call__()s. If there is no __get__, the object is called as is, without passing self.

Consider this, for example:

>>> class Foo:
...     def method(self):
...             print("hi")
... 
>>> f = Foo()
>>> f.method
<bound method Foo.method of <__main__.Foo object at 0x7f58edb5f310>>
>>> Foo.method
<function Foo.method at 0x7f58edb30790>
>>> Foo.m…

Replies: 2 comments 8 replies

Comment options

You must be logged in to vote
8 replies
@Akuli
Comment options

@tobinus
Comment options

@Akuli
Comment options

@tobinus
Comment options

@tobinus
Comment options

Answer selected by tobinus
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants