which a is used?

Dwight Hutto dwightdhutto at gmail.com
Mon Sep 24 21:47:04 EDT 2012


On Mon, Sep 24, 2012 at 9:18 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Mon, 24 Sep 2012 16:43:24 -0700, Jayden wrote:
>
>> Dear All,
>>
>> I have a simple code as follows:
>>
>> # Begin
>> a = 1
>>
>> def f():
>>     print a
>>Paul Rubin <no.email at nospam.invalid>
>> def g():
>>     a = 20
>>     f()
>>
>> g()
>> #End
>>
>> I think the results should be 20, but it is 1. Would you please tell me
>> why?
>
> You are expecting "dynamic scoping", Python uses "static scoping" (or
> lexical scoping). With lexical scoping, you can reason about the
> behavioPaul Rubin <no.email at nospam.invalid>ur of a function by knowing only how and where it is defined. The
> caller is irrelevant.
>
> Since fuPaul Rubin <no.email at nospam.invalid>nction f is defined globally, and does not have its own local
> variable a, it will always see the global variable a no matter where it
> is called. So when you call f() from inside g(), f prints 1, the global
> a, not 20, g's local a.
>
> While dynamic scoping has its uses, it is more tricky to use correctly.
> One can no longer understand the behaviour of a function just by reading
> the funcPaul Rubin <no.email at nospam.invalid>tion's own code, knowing where and how it is defined. You also
> need to know where it is called. A function f that works perfectly when
> you call it from functions g, h, k, ... will suddenly misbehave (crash,
> or worse, behave wrongly) when called from function v because v
> accidentally changes some global variable that f relies on.
>
> This is especially a danger for Python, because built-in functions like
> len, chr, ord, print (version 3 only), and many others are all global
> variables.
>
> (Technically, they are in a third scope, the builtins, but that's
> equivalent to being global.)
>

But within a class this is could be defined as self.x within the
functions and changed, correct?


class a():
	def __init__(self,a):
		self.a = a

	def f(self):
		print self.a

	def g(self):
		self.a = 20
		print self.a


a = a(1)
a.f()
a.g()


> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list



-- 
Best Regards,
David Hutto
CEO: http://www.hitwebdevelopment.com



More information about the Python-list mailing list