Consider the following code, why don't I need to pass x to Y?
class X:
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
class Y:
def A(self):
print(x.a,x.b,x.c)
x = X()
y = Y()
y.A()
Thank you to the top answers, they really helped me see what was the problem, namely misunderstanding regarding variable scope. I wish I could choose both as correct answer as they are enlightening in their own way.
It takes it from current scope. If you remove
x = X()
it will throw a error.You can use variables from current scope and variable from all parent scopes inside a function.
For details on how scope is defined check python language reference on Naming and Binding
Also, since you are not changing x it works just fine. But if you would've try to change variable from parent scope it would throw error:
In such case you need to use
global
keyword:From The Python Tutorial:
In your case
x=X()
putsx
into the global namespace. Since you did not definex
locally inY.A
(innermost scope), python searches for the variable definition using the above rules and finds that 'x' is defined in the outermost scope. Therefore when you referencex.a
inY.A
it resolves just fine.Python looks up variables by first looking in the local scope (i.e. within a function) and if does not find it, it will use the variable from the global scope, if it exists. After that it will look for Python built-in names.
When the statement
y = Y()
is reached,x
has already been declared in the global scope. This means that when the functionA(self)
is called,x
can be looked up in the global scope.More information about variable scope can be found here: Short Description of the Scoping Rules?
It's because you've instantiated x=X(), so that x.a, x.b, and x.c can be accessed. If you try z=X(), you'll notice it doesn't work.
When python compiles a
def
into a function, it tries to figure out if the things you are referencing are locals - and if they're not, you must be referring to a global. For example:Well, you haven't defined
x
within the scope off
, so you must be referring to a global.This is all that's happening in your above code. You haven't defined
x
within the scope ofA
, sox
must be a global. As it happens, you define the global:before you call it:
so everything works out okay.
In case you are going "hm, I'm not sure if I believe you, roippi" just look at the bytecode:
aha.