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.
解决方案Although scopes are determined statically, they are used dynamically.
At any time during execution, there are at least three nested scopes
whose namespaces are directly accessible:
the innermost scope, which is searched first, contains the local names
the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also
non-global names the next-to-last scope contains the current module’s
global names the outermost scope (searched last) is the namespace containing built-in names
In your case x=X() puts x into the global namespace. Since you did not define x locally in Y.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 reference x.a in Y.A it resolves just fine.