473,473 Members | 2,111 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Beginner's scoping question

a=1
b=[]
class C():
def __init__(self):
a=2
b.append(3)

c = C()

print b
# [3]

# but ...
print a
# 1

???
Jul 18 '05 #1
6 1251
If you make an assignment in a method, the name assumes a local scope in
python. "b" was not assigned so did not assume local scope.

James

On Wednesday 10 November 2004 12:40 pm, Alan Little wrote:
a=1
b=[]
class C():
def __init__(self):
a=2
b.append(3)

c = C()

print b
# [3]

# but ...
print a
# 1

???


--
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
611 Charles E. Young Dr. S.
MBI 205, UCLA 951570
Los Angeles CA 90095-1570
http://www.jamesstroud.com/
Jul 18 '05 #2
Hi,

You need to declare "a" as global before when you assign something to it
inside a function.

def __init__(self):
global a
a = 2

-Farshid

"Alan Little" <co*****@alanlittle.org> wrote in message
news:4e**************************@posting.google.c om...
a=1
b=[]
class C():
def __init__(self):
a=2
b.append(3)

c = C()

print b
# [3]

# but ...
print a
# 1

???

Jul 18 '05 #3
co*****@alanlittle.org (Alan Little) wrote in message news:<4e**************************@posting.google. com>...
a=1
b=[]
class C():
def __init__(self):
a=2
b.append(3)

c = C()

print b
# [3]

# but ...
print a
# 1

???


The key points are as follows:

The statement 'a=2' simply assigns the 'name' 'a' the value '2' within
the local scope of your __init__ function.

If a name does not exist in the local scope at the time of an
assignment, the name will be created within the local scope, rather
than attempting to look up the name in an enclosing scope.

On the other hand, had there already been an identifier named 'a'
within the __init__ function, the assignment would have simply
assigned the value '2' to the name 'a' regardless of what 'a'
originally referred to.

Now, the statement 'b.append(3)' is not an assignment statement. For
this reason, there is no attempt to bind an object to the name 'b'.
In fact, the method 'append' is called, which implies that 'b' is
already bound to an object that implements an 'append' method (if not,
an AttributeError exception will be raised when the object named 'b'
is found, assuming it is found).

Thus, in order to call 'append' on 'b', 'b' must first be found.
First the local scope is searched for the name 'b' (your __init__
method). After failing to find it, the enclosing scope is searched,
where the name 'b' was found.

For this reason, the code:

b=[]
class C:
def __init__(self):
b=[]
b.append(3)

c = C()
print b

would print out '[]', as I presume you expect. The key to this
behavior is the assignment statement (i.e. b=[]) within the scope of
the __init__ method.

Regards,

Michael Loritsch
Jul 18 '05 #4
On 10 Nov 2004 12:40:34 -0800, co*****@alanlittle.org (Alan Little)
wrote:
a=1
b=[]
class C(): is should be...
class C: # whithout the () def __init__(self):
a=2
b.append(3)

c = C()

print b
# [3]

# but ...
print a
# 1

???

a=1
b=[]
class C:
def __init__(self):
global a # !!!!!!!!!!!
a=2
b.append(3)

c = C()

print b
# [3]

# but ...
print a
# 2

a in the class is a local to that class and because it in not assiged
to self.a it is also not normally addressable outside the class
if you want to change the already existing global a you have to
declare it global (see code)

You try to append to a non-existing local variable b.
Python first tries the local() namespace and then the global()
it finds b in the global namespace and appends the value.

cheerz,
Ivo
Jul 18 '05 #5
Premshree Pillai <premshree_python <at> yahoo.co.in> writes:

class C():

is incorrect. Should be

class C:


Or better yet:

class C(object):
...

Unless you're targeting older versions of Python, you probably want to be
creating new-style classes, not old-style classes. Old-style classes are really
only present for backwards-compatibility, and will go away in Python 3000.

Steve

Jul 18 '05 #6
Very helpful and informative responses guy. Thanks. I was surprised
that the assignment in the __init__ wouldn't search the enclosing
scope first before creating a new local. But if that's the way it
works, that's the way it works. Now I now.
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: David Stockwell | last post by:
Hi, Another of my crazy questions. I'm just in the process of learning so bear with me if you can. I actually ran it.... with two test cases TEST CASE 1: Say I have the following defined:...
8
by: It's me | last post by:
This must be another newbie gotchas. Consider the following silly code, let say I have the following in file1.py: #============= import file2 global myBaseClass myBaseClass =...
4
by: Frederick Grim | last post by:
okay so the code in question looks like: namespace util { template<typename C> inline void mmapw(C *& ptr, size_t length, int prot, int flags, int fd, off_t offset) { if((ptr =...
4
by: Joel Gordon | last post by:
Hi, When I try and compile the a class containing the following method : public void doSomething() { for (int i=0; i<5; i++) { IList list = new ArrayList(); Console.WriteLine( i /...
4
by: Sohum | last post by:
Hi I'm reasonably new to this group, and to programming in general. I'd like to know, can you selectively scope within an interface? For example: Public Interface MyInterface Friend...
13
by: Ranginald | last post by:
I am new to oop so please bear with me: Could someone please explain to me why the "protected void runCategory() method" cannot access the local ddlCategory object that is easily accessed in...
9
by: NevilleDNZ | last post by:
Can anyone explain why "begin B: 123" prints, but 456 doesn't? $ /usr/bin/python2.3 x1x2.py begin A: Pre B: 123 456 begin B: 123 Traceback (most recent call last): File "x1x2.py", line 13,...
3
by: morris.slutsky | last post by:
So every now and then I like to mess around with hobby projects - I often end up trying to write an OpenGL video game. My last attempt aborted due to the difficulty of automating game elements and...
17
by: Chad | last post by:
The following question stems from Static vs Dynamic scoping article in wikipedia. http://en.wikipedia.org/wiki/Scope_(programming)#Static_versus_dynamic_scoping Using this sites example, if I...
3
by: SPECTACULAR | last post by:
Hi all. I have a question here.. what kind of scoping does C++ use? and what kind does Smalltalk use? I know smalltalk is a little bit old .. but any help would be appreciated.
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.