Why is this closure not possible in python? -
in python able access variable in outer function inner function , hence forms closure. however, not able access variable in outer class inner class this,
>>> class a: ... a=1 ... class b: ... b=1 ... def pr(self): ... print a,b ... >>> c=a().b() >>> c.pr() traceback (most recent call last): file "<stdin>", line 1, in <module> file "<stdin>", line 6, in pr nameerror: global name 'a' not defined
why kind of closure not possible in python?
the docs say:
the scope of names defined in class block limited class block; not extend code blocks of methods
the scope of class block not extend code blocks of nested class statements.
it's not clear (to me) trying do, here more typical pattern makes b
subclass of a
, allows instances of b
access attributes of both b
, a
:
class a: a=1 class b(a): b=1 def pr(self): print self.a, self.b c = b() c.pr()
prints
1 1
Comments
Post a Comment