473,804 Members | 3,228 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Lists in classes

Hello,

Learning python from a c++ background. Very confused about this:

============
class jeremy:
list=[]
def additem(self):
self.list.appen d("hi")
return

temp = jeremy()
temp.additem()
temp.additem()
print temp.list

temp2 = jeremy()
print temp2.list
==============
The output gives:
['hi','hi']
['hi','hi']

Why does adding items to one instance produce items in a separate
instance? Doesn't each instance of jeremy have its' own "list"?

Many thanks for clearing up this newbie confusion.

Jeremy.

Jul 12 '07 #1
9 1312
On 12 jul, 17:23, Jeremy Lynch <jeremy.ly...@g mail.comwrote:
Hello,

Learning python from a c++ background. Very confused about this:

============
class jeremy:
list=[]
def additem(self):
self.list.appen d("hi")
return

temp = jeremy()
temp.additem()
temp.additem()
print temp.list

temp2 = jeremy()
print temp2.list
==============
The output gives:
['hi','hi']
['hi','hi']

Why does adding items to one instance produce items in a separate
instance? Doesn't each instance of jeremy have its' own "list"?
You've defined list (very bad choice for a name), as a class variable.
To declare instance variable you should have written:
class jeremy:

Jul 12 '07 #2
On Jul 12, 10:23 am, Jeremy Lynch <jeremy.ly...@g mail.comwrote:
Hello,

Learning python from a c++ background. Very confused about this:

============
class jeremy:
list=[]
def additem(self):
self.list.appen d("hi")
return

temp = jeremy()
temp.additem()
temp.additem()
print temp.list

temp2 = jeremy()
print temp2.list
==============
The output gives:
['hi','hi']
['hi','hi']

Why does adding items to one instance produce items in a separate
instance? Doesn't each instance of jeremy have its' own "list"?

Many thanks for clearing up this newbie confusion.

Jeremy.
The reason it works like that is that your variable "list" isn't an
instance variable per se. Instead, you should have it like this:

<code>

class jeremy:
def __init__(self):
self.lst=[]
def additem(self):
self.lst.append ("hi")
return

</code>

Now it works as expected. It's some kind of scope issue, but I can't
explain it adequately.

Mike

Jul 12 '07 #3
On 12 jul, 17:23, Jeremy Lynch <jeremy.ly...@g mail.comwrote:
Hello,

Learning python from a c++ background. Very confused about this:

============
class jeremy:
list=[]
You've defined list (very bad choice of a name, BTW), as a class
variable. To declare is as instance variable you have to prepend it
with "self."

Jul 12 '07 #4
On Jul 12, 6:23 pm, Jeremy Lynch <jeremy.ly...@g mail.comwrote:
Hello,

Learning python from a c++ background. Very confused about this:

============
class jeremy:
list=[]
def additem(self):
self.list.appen d("hi")
return

temp = jeremy()
temp.additem()
temp.additem()
print temp.list

temp2 = jeremy()
print temp2.list
==============
The output gives:
['hi','hi']
['hi','hi']

Why does adding items to one instance produce items in a separate
instance? Doesn't each instance of jeremy have its' own "list"?

Many thanks for clearing up this newbie confusion.

Jeremy.
You are defining the list in the class context and so it becomes a
class field/member.
For defining instance members you need to always prefix those with
self (this) in the
contexts it is available (f.e. in the instance method context).

bests,

../alex
--
..w( the_mindstorm )p.
Jul 12 '07 #5
Jeremy Lynch wrote:
Hello,

Learning python from a c++ background. Very confused about this:

============
class jeremy:
list=[]
def additem(self):
self.list.appen d("hi")
return

temp = jeremy()
temp.additem()
temp.additem()
print temp.list

temp2 = jeremy()
print temp2.list
==============
The output gives:
['hi','hi']
['hi','hi']

Why does adding items to one instance produce items in a separate
instance? Doesn't each instance of jeremy have its' own "list"?

Many thanks for clearing up this newbie confusion.

Jeremy.
In this code, "list" (bad name) is a class attribute and all therefor in
all instances, the "list" attribute is reference to the class attribute
unless otherwise assigned, as in __init__.

For instance, try:
temp = jeremy()
temp.additem()
temp.additem()
print temp.list

temp2 = jeremy()
temp2.list = [1,2,3]
print temp.list, temp2.list, jeremy.list
And see which ones look the same (same reference) or look different.

James
Jul 12 '07 #6
Bart Ogryczak wrote:
On 12 jul, 17:23, Jeremy Lynch <jeremy.ly...@g mail.comwrote:
>Hello,

Learning python from a c++ background. Very confused about this:

============
class jeremy:
list=[]

You've defined list (very bad choice of a name, BTW), as a class
variable. To declare is as instance variable you have to prepend it
with "self."

Ouch!

'self' is *not* a reserved ord in python, it doesn't do anything. So
just popping 'self' in front of something doesn't bind it to an instance.
Here is how it works:

class Jeremy(object): # you better inherit from 'object' at all times
classlist = [] # class variable
def __init__(self): # "constructo r"
self.instanceli st = [] # instance variable
def add_item(self, item):
self.instanceli st.append(item)

'self' is the customary name for the first argument of any instance
method, which is always implicitly passed when you call it. I think it
translates to C++'s 'this' keyword, but I may be wrong. Simply put: The
first argument in an instance-method definition (be it called 'self' or
otherwise) refers to the current instance.
Note however that you don't explicitly pass the instance to the method,
that is done automatically:

j = Jeremy() # Jeremy.__init__ is called at this moment, btw
j.add_item("hi" ) # See? 'item' is the first arg you actually pass

I found this a bit confusing at first, too, but it's actually very
clean, I think.
/W
Jul 12 '07 #7
Thanks for all the replies, very impressive. Got it now.

Jeremy.

On Jul 12, 4:23 pm, Jeremy Lynch <jeremy.ly...@g mail.comwrote:
Hello,

Learning python from a c++ background. Very confused about this:

============
class jeremy:
list=[]
def additem(self):
self.list.appen d("hi")
return

temp = jeremy()
temp.additem()
temp.additem()
print temp.list
>
temp2 = jeremy()
print temp2.list
==============
The output gives:
['hi','hi']
['hi','hi']

Why does adding items to one instance produce items in a separate
instance? Doesn't each instance of jeremy have its' own "list"?

Many thanks for clearing up this newbie confusion.

Jeremy.

Jul 12 '07 #8
Alex Popescu a écrit :
(snip)
>
You are defining the list in the class context and so it becomes a
class field/member.
'attribute' is the pythonic term.
Jul 12 '07 #9
On Jul 13, 6:02 am, Bruno Desthuilliers
<bdesth.quelque ch...@free.quel quepart.frwrote :
Alex Popescu a écrit :
(snip)
You are defining the list in the class context and so it becomes a
class field/member.

'attribute' is the pythonic term.

Thanks! I'm just a couple of weeks Python old, so I am still fighting
to use the correct vocabulary :-).
And as with foreign languages, while I am becoming better at reading I
still have problems expressing
correct ideas using correct words.

../alex
--
..w( the_mindstorm )p.

Jul 15 '07 #10

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

Similar topics

42
2766
by: Jeff Wagner | last post by:
I've spent most of the day playing around with lists and tuples to get a really good grasp on what you can do with them. I am still left with a question and that is, when should you choose a list or a tuple? I understand that a tuple is immutable and a list is mutable but there has to be more to it than just that. Everything I tried with a list worked the same with a tuple. So, what's the difference and why choose one over the other? Jeff
2
8258
by: Kakarot | last post by:
I'm gona be very honest here, I suck at programming, *especially* at C++. It's funny because I actually like the idea of programming ... normally what I like I'm atleast decent at. But C++ is a different story. Linked lists have been giving me a headache. I can barely manage to create a single/doubly linked list, it's just that when it gets to merge sorting or searching (by reading shit data from text files), I lose track.
7
4834
by: Chris Ritchey | last post by:
Hmmm I might scare people away from this one just by the title, or draw people in with a chalange :) I'm writting this program in c++, however I'm using char* instead of the string class, I am ordered by my instructor and she does have her reasons so I have to use char*. So there is alot of c in the code as well Anyways, I have a linked list of linked lists of a class we defined, I need to make all this into a char*, I know that I...
0
3558
by: Jimmy Cerra | last post by:
I recently came up with a cool little stylesheet for definition lists. There is a small demostration for the impatient . I hope this helps someone. Here's how I did it. Definition lists are usually styled something like: ] Term ] A tab of white space followed by the definition ] By
1
1498
by: andrew | last post by:
Hi, I'm a C++ newbie, so apologies for this rather basic question. I've searched for help and, while I understand the problem (that the outer class is not yet defined), I don't understand what the "correct" solution would be. I am trying to model lists much like in Lisp, using a "Cons" object to hold two pointers - one to an Element, and the other to a further Cons. Cons is a subclass of Element, so lists can be nested.
3
1670
by: Claudio Grondi | last post by:
Trying to understand the outcome of the recent thread (called later reference thread): "Speed quirk: redundant line gives six-fold speedup" I have put following piece of Python code together: class PythonObject_class: pass PythonObject_class_instanceA = PythonObject_class()
9
4965
by: Paulo da Silva | last post by:
Hi! What is the best way to have something like the bisect_left method on a list of lists being the comparision based on an specified arbitrary i_th element of each list element? Is there, for lists, something equivalent to the __cmp__ function for classes? Thanks.
5
2068
by: Gordon Airporte | last post by:
This is one of those nice, permissive Python features but I was wondering how often people actually use lists holding several different types of objects. It looks like whenever I need to group different objects I create a class, if only so I can use more meaningful names than '' for the items. How often do these show up in your code? Is this simply the upshot of the underlying arrays holding only object references of some sort?
1
2868
by: colin | last post by:
Hi, I have 3 object of interest wich are objects in 3d space, surface,wire,point. they are all interconnected, and they all contain lists of objects they are connected to, eg each surface will have a list of wires, points, and adjacent surfaces. same for the others. building the lists so they all the references are two way is fairly easy to
0
1005
by: twdesign | last post by:
I am a Python newbie! I'm trying to list the feature classes in a dataset (Access .MDB) and then list the fields in each feature class. I'm able to list the feature classes and I'm able to list the fields in a particular feature class if I name it specifically. For example, PARCEL is one of the feature classes listed in the dataset return. If I put "PARCEL" in the list fields criteria I get the field information for parcels. I would like...
0
9708
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, 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...
0
9588
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,...
0
10589
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10340
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10327
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,...
0
9161
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, 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...
0
5527
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...
0
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4302
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 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.