1

I am trying to understand the following python snippet:

 x = SomeObject
 x = SomeClass(some_input)(x)

Can anyone shed some light on what is going on here?

Oblomov
  • 8,953
  • 22
  • 60
  • 106
  • 1
    `SomeClass` is apparently callable, so when you create an instance – `y = SomeClass(some_input)` – you can call it: `y(…)`. – Ry- Jan 10 '17 at 18:26
  • Can you provide the definitions for `SomeObject` and `SomeClass`? – Tagc Jan 10 '17 at 18:37
  • The class definition is a bit too involved to post it here. But thanks for pointing me to the direction of "callable classes", I obviously need to look into that concept to understand this syntax. – Oblomov Jan 10 '17 at 18:40

2 Answers2

3

It can be simplified to the following (assuming that the auxiliary variables y and z are not used by surrounding code):

y = SomeObject
z = SomeClass(some_input)
x = z(y)
Leon
  • 31,443
  • 4
  • 72
  • 97
  • 1
    Thanks for your answer. But what is happening here: x = z(y) ? Looks like a function call, but z is an object of SomeClass and not a function... – Oblomov Jan 10 '17 at 18:30
  • 1
    In the expression `z(y)` `z` must be a [callable](http://stackoverflow.com/questions/111234/what-is-a-callable-in-python) object (functions are just one example of callable objects). – Leon Jan 10 '17 at 19:20
1

Extending others response will try to give you a more general answer, on how Python will solve that statement

x = SomeClass(some_input)(x)

First Python's interpreter will try solve the statement after the = and then assign it to x, so this leave us with_

SomeClass(some_input)(x)

In this statement there are two main elements the SomeClass instation and the call for the result instance that should be a callable)

SomeClass(some_input):  (x)
#---instantiation----:--call--

It will solve first the left-side to determine what should be called, in the left-side We have a Class instantiation, it means that Python interpreter will call the SomeClass.__init__(...) method with the arguments (some_input). This involves that if some_input is a call of a method, instantiation, formula or so itself, it will try to solve that first.

SomeClass(some_input) # => <new object>

This <new_object> is the one who will be called with the arguments (x) and this is possible because the SomeClass can (and should in this example) be callable just with implementing the __call__ method as you would do with __init__, as example:

class Add:
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2
        print "Sum of", self.num1,"and",self.num2, "is:"

    def __call__(self):
        return (self.num1 + self.num2)

add = Add(1,2)
print add()

+More info about objects being callables

note: The reference <new_object>, as it not bound with any variable, will be lost after the last statement.

Rafael Aguilar
  • 3,084
  • 1
  • 25
  • 31