Why does this function output 0 1
?
Why is a class in a function behaving like a function? Why didn't I have to call A like a function?
How does the assignment statement after print()
affect the values of x
and y
? When I assign value to x
, x
becomes 0 and if I assign a value to y
, y
becomes 0.
x = 0
y = 0
def f():
x = 1
y = 1
class A:
print(x,y)
x = 99
f()
The act of assignment to a variable allocates the name and space for the variable to contain a value. We saw that we can assign a variable a numeric value as well as a string (text) value. We also saw that we can re-assign a variable, providing it a new value which replaces any previous value it contained.
No worries you can assign print() statement to the variable like this. According to the documentation, All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end.
As mentioned above, the print statement is used to output all kinds of information. This includes textual and numerical data,variables, and other data types. You can also print text (or strings) combined with variables, all in one statement. You'll see some of the different ways to do this in the sections that follow.
The simple assignment operator ( = ) is used to assign a value to a variable. The assignment operation evaluates to the assigned value.
From the Python 3.9 documentation :
If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block.
The line x = 99
in the class definition, makes x
local to the class block.
In a class block,
References follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace.
At the point the print(x,y)
is executed, x
is an unbound local variable. It's value is looked up in the global namespace, where x = 0
.
When a name is used in a code block, it is resolved using the nearest enclosing scope.
When print(x, y)
is executed, the value of y
is looked up in the nearest enclosing scope, which is the body of def f()
, where y = 1
.
So print(x, y)
outputs 0 1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With