0

I'm trying to understand someone else's code in Python and I stumbled across a line I don't quite understand and which I can't find on the internet:

x=self(k)

with k being a torch-array. I know what self.something does but I haven't seen self(something) before.

2
  • 3
    This means that self is callable, indicating that this class may implement __call__ magic method. Commented Sep 6, 2022 at 16:57
  • 2
    If self is within a nn.Module, then this calls the containing class's forward method (which is invoked from __call__ as @MechanicPig points out). Commented Sep 6, 2022 at 16:58

1 Answer 1

3

self, for these purposes, is just a variable like any other, and when we call a variable with parentheses, it invokes the __call__ magic method. So

x = self(k)

is effectively a shortcut for

x = self.__call__(k)

Footnote: I say "effectively", because it's really more like

x = type(self).__call__(self, k)

due to the way magic methods work. This difference shouldn't matter unless you're doing funny things with singleton objects, though.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.