Reputation: 9635
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?
Upvotes: 1
Views: 84
Reputation: 3279
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.
Upvotes: 1
Reputation: 32484
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)
Upvotes: 3