hey,
okay, I'm trying to figure out why my books: Quick Python, Python in a
Nutshell, Python Cookbook and Learning Python don't say anything about the
weird behavior of a list when you have one as an object instance member.
for instance (my first pun of 2004), if I have,
test.py
----------------
global_filegrou p_array = [] # array of filegroup objects
class FileGroup:
a = 0
mylist = [] # here it is
def put_stuff_in_my _list(self, anyfile):
self.mylist.app end( get just a single string from file) #
pls excuse the psuedo
def __init__(self):
put_stuff_in_my _list(anyfile)
def main(): # do ten times: instantiate the
above object, and add to the global array
for i in xrange(10):
filegroup = FileGroup()
global_filegrou p_array.append( filegroup)
# print the list contents
print global_filegrou p_array[0].mylist
------------ end of file
Output is: [u'.string1', u'.string2', u'.string3' ] # only
u'string1' should show up
No matter which index I use into the global array, I always get ALL of
the strings
showing up. I should only get u'string1' showing up, and u'string2'
if
I used "[1].mylist"
How I resolved it, is by slipping in
self.mylist = []
before
put_stuff_in_my _list(anyfile)
in __init__(self)
Why should I have to empty out the list when it's a member of a newly
instantiated object?
thanks
p.s. ( I'm actually not doing exactly the thing with the
files, but instead iterating through a xml file with dom,
debugging it showed the behavior ) 5 1458
In article <ff************ *****@newssvr29 .news.prodigy.c om>, python
newbie <me*******@hotm ail.com> writes
I think you're not grokking that using
class A:
mylist = []
makes mylist a class attribute ie all instances share the same version
of mylist. To get an instance version you need to assign self.mylist.
That would normally be done using an __init__method. so
class A:
def __init__(self):
self.mylist = []
then each instance sets up its own empty list at creation time.
Hope that helps.
--
Robin Becker
python newbie wrote: test.py ----------------
global_filegrou p_array = [] # array of filegroup objects
class FileGroup: a = 0 mylist = [] # here it is
This is a class variable, not a member or instance variable. Make
sure you know the difference.
def put_stuff_in_my _list(self, anyfile): self.mylist.app end( get just a single string from file)
This line creates a member variable "mylist" of the current instance
"self" of class "FileGroup" as a copy of the class variable
"FileGroup.myli st".
Just create your member variables in the c'tor function __init__.
This should solve all your problems (ok, at least this problem;)
And btw. Python in a nutshell (I haven't read the other books you've
mentioned) explains the differences between class and member
variables.
Mathias
In article <ff************ *****@newssvr29 .news.prodigy.c om>, python newbie wrote: hey, okay, I'm trying to figure out why my books: Quick Python, Python in a Nutshell, Python Cookbook and Learning Python don't say anything about the weird behavior of a list when you have one as an object instance member.
for instance (my first pun of 2004), if I have,
test.py ----------------
global_filegrou p_array = [] # array of filegroup objects
class FileGroup: a = 0 mylist = [] # here it is
mylist in this case is a class variable; what this means is that it is shared
amongst all *instances* of the class. Only if an instance of the class rebinds
mylist is it local to the particular class instance doing this. def put_stuff_in_my _list(self, anyfile): self.mylist.app end( get just a single string from file) # pls excuse the psuedo
Because lists are mutable, when you use mylist.append(. ..) you don't rebind
mylist, but change its contents. Since mylist is a class variable, this
change is available to the class as well as all instances of the class. def __init__(self): put_stuff_in_my _list(anyfile)
def main(): # do ten times: instantiate the above object, and add to the global array for i in xrange(10): filegroup = FileGroup() global_filegrou p_array.append( filegroup)
# print the list contents print global_filegrou p_array[0].mylist
------------ end of file
Output is: [u'.string1', u'.string2', u'.string3' ] # only u'string1' should show up
No matter which index I use into the global array, I always get ALL of the strings showing up. I should only get u'string1' showing up, and u'string2' if I used "[1].mylist"
How I resolved it, is by slipping in
self.mylist = []
before
put_stuff_in_my _list(anyfile)
in __init__(self)
Why should I have to empty out the list when it's a member of a newly instantiated object?
Because __init__() is called when a class is about to be instantiated. You are
masking the *class variable* mylist with a local *instance variable* of the
same name. The latter is not shared amongst all instances of the class, but
remains unique to the particular instance.
Hope this helps,
/Troels Therkelsen
thanks for the helpful replies.
I guess I was just in confusion as to why I was able to leave alone the
string variables in class FileGroup, such
as sourceDir and destinDir, and nothing unpredictable happened with those,
but with the list variable, I had to treat differently.
But after I again read closely, Python In a Nutshell, I'm sure I will
understand.
"python newbie" <me*******@hotm ail.com> wrote in message
news:ff******** *********@newss vr29.news.prodi gy.com... hey, okay, I'm trying to figure out why my books: Quick Python, Python in a Nutshell, Python Cookbook and Learning Python don't say anything about the weird behavior of a list when you have one as an object instance member.
for instance (my first pun of 2004), if I have,
test.py ----------------
global_filegrou p_array = [] # array of filegroup objects
class FileGroup: a = 0 mylist = [] # here it is
def put_stuff_in_my _list(self, anyfile): self.mylist.app end( get just a single string from file) # pls excuse the psuedo
def __init__(self): put_stuff_in_my _list(anyfile)
def main(): # do ten times: instantiate the above object, and add to the global array for i in xrange(10): filegroup = FileGroup() global_filegrou p_array.append( filegroup)
# print the list contents print global_filegrou p_array[0].mylist
------------ end of file
Output is: [u'.string1', u'.string2', u'.string3' ] # only u'string1' should show up
No matter which index I use into the global array, I always get ALL of the strings showing up. I should only get u'string1' showing up, and u'string2' if I used "[1].mylist"
How I resolved it, is by slipping in
self.mylist = []
before
put_stuff_in_my _list(anyfile)
in __init__(self)
Why should I have to empty out the list when it's a member of a newly instantiated object?
thanks
p.s. ( I'm actually not doing exactly the thing with the files, but instead iterating through a xml file with dom, debugging it showed the behavior )
I didn't say that right. I meant to say that I now finally understood
what's going on now, with your replies, but I will take a slight break from
the app I'm writing, and do some ingesting of the core Python concepts.
"python newbie" <me*******@hotm ail.com> wrote in message
news:Vf******** ********@newssv r29.news.prodig y.com... thanks for the helpful replies. I guess I was just in confusion as to why I was able to leave alone the string variables in class FileGroup, such as sourceDir and destinDir, and nothing unpredictable happened with those, but with the list variable, I had to treat differently. But after I again read closely, Python In a Nutshell, I'm sure I will understand. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Charlotte Henkle |
last post by:
Hello;
I'm pondering how to count the number of times an item appears in
total in a nested list. For example:
myList=,,]
I'd like to know that a appeared three times, and b appeared twice,
and the rest appeard only once.
|
by: Jacek Dziedzic |
last post by:
Hi!
A) Why isn't it possible to set a member of the BASE class in
an initialization list of a DERIVED class constructor (except for
'calling' the base constructor from there, of course)? I even
tried prefixing them with BASE:: but to no avail. Still it's
ok when I set them in the construtor body, not the init list.
Does this mean that it's a small advantage of the initialization
inside the constructor over initialization in the init...
|
by: Jacek Dziedzic |
last post by:
Hello!
Suppose I have a class Foo that defines a default c'tor
that initializes some data using an initialization list:
Foo::Foo() : member1(0), member2(0), member3(NULL), member4(20)
// and so on, quite a few members
{}
and does nothing else.
|
by: V_S_H_Satish |
last post by:
Dear Friends
I am working as oracle and ms sql dba from last 4 years. My company
recently migrated to DB2 databases.
So i am very much new to db2 database
Can any one pls provide script to do daily db2 check lists.
The following colums i need in the daily check lists
|
by: pasa_1 |
last post by:
Can someone clarify few items from FAQ
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6
' Should my constructors use "initialization lists" or
"assignment"?'
a. This might happen when your class has two constructors that need to
initialize the 'this' object's data members in different orders. <--
Okay
| |
by: =?Utf-8?B?QkogU2FmZGll?= |
last post by:
We have a class that has a public property that is of type List<T>. FXCop
generates a DoNotExposeGenericLists error, indicating
"System.Collections.Generic.List<Tis a generic collection designed for
performance not inheritance and, therefore, does not contain any virtual
members. The following generic collections are designed for inheritance and
should be exposed instead of System.Collections.Generic.List<T>.
*...
|
by: Jeremy Lynch |
last post by:
Hello,
Learning python from a c++ background. Very confused about this:
============
class jeremy:
list=
def additem(self):
self.list.append("hi")
return
|
by: Jeff |
last post by:
..NET 2.0
Is generic lists faster then tradional lists when sending over a collection
of objects (value by reference) in .NET remoting.
Lets say if a list of object should be sent from a server to the client.
Whould it be better to use generic lists?
Jeff
|
by: John A Grandy |
last post by:
InstrumentPropertyEntity
string Name
InstrumentEntity
string Name
List<InstrumentPropertyEntityInstrumentProperties
For a List<InstrumentEntity, I want to determine the
List<InstrumentPropertyEntityheld in common by all members.
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |