Search code examples
pythonobjectassignment-operator

In x = 1, are both x and 1 objects?


In x = 1, are both x and 1 objects? Because print(1) and x = 1; print(x) will result in the same output.

Even the syntax of print function is:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)


Solution

  • Names in Python are not objects. Using a name in an expression automatically evaluates to the object referred to by the name. It is not possible to interact with the name itself in any way, such as passing it around or calling a method on it.

    >>> x = 1
    >>> type(1)    # pass number to function...
    <class 'int'>  # ...and receive the number!
    >>> type(x)    # pass name to function...
    <class 'int'>  # ...but receive the target!
    

    Note that technically, 1 is also not an object but a literal of an object. Only the object can be passed around – it does not reveal whether it originates from a literal 1 or, for example, a mathematical expression such as 2 - 1.