473,396 Members | 1,891 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Is a list static when it's a class member?

I have a class with a list member and the list seems to behave like
it's static while other class members don't. The code...

class A:
name = ""
data = []
def __init__(self, name):
self.name = name
def append(self, info):
self.data.append(info)
def enum(self):
for x in self.data:
print "\t%s" % x

a = A("A:")
print a.name
a.append("one")
a.append("two")
a.enum()
b = A("B:")
print b.name
b.append("horse")
b.append("bear")
b.enum()
print a.name
a.enum()

The output...
>>>
A:
one
two
B:
one
two
horse
bear
A:
one
two
horse
bear
>>>
How do i get:
A:
one
two
B:
horse
bear
A:
one
two

Thanks,

glue

Oct 10 '06 #1
9 1448
glue wrote:
I have a class with a list member and the list seems to behave like
it's static while other class members don't. The code...

class A:
name = ""
data = []
def __init__(self, name):
self.name = name
def append(self, info):
self.data.append(info)
def enum(self):
for x in self.data:
print "\t%s" % x

a = A("A:")
print a.name
a.append("one")
a.append("two")
a.enum()
b = A("B:")
print b.name
b.append("horse")
b.append("bear")
b.enum()
print a.name
a.enum()

The output...
A:
one
two
B:
one
two
horse
bear
A:
one
two
horse
bear

How do i get:
A:
one
two
B:
horse
bear
A:
one
two

Thanks,

glue

I can already tell you that this does it:

class A:
name = ""
def __init__(self, name):
self.data = []
self.name = name
def append(self, info):
self.data.append(info)
def enum(self):
for x in self.data:
print "\t%s" % x

Somebody else can explain the reason. I just don't wanna write something
that I'm not sure of. :-)

Regards,
antoine
Oct 10 '06 #2
class A:
name = ""
data = []
def __init__(self, name):
self.name = name
def append(self, info):
self.data.append(info)
def enum(self):
for x in self.data:
print "\t%s" % x
How do i get:
A:
one
two
B:
horse
bear
A:
one
two

class A:
name = ""
# data = [] # just move this line
def __init__(self, name): #
self.name = name #
self.data = [] # here
def append(self, info):
self.data.append(info)
def enum(self):
for x in self.data:
print "\t%s" % x
It will be given a "fresh" list upon each __init__ call.

-tkc
Oct 10 '06 #3
glue wrote:
I have a class with a list member and the list seems to behave like
it's static while other class members don't. The code...

class A:
name = ""
data = []
def __init__(self, name):
self.name = name
def append(self, info):
self.data.append(info)
def enum(self):
for x in self.data:
print "\t%s" % x

a = A("A:")
print a.name
a.append("one")
a.append("two")
a.enum()
b = A("B:")
print b.name
b.append("horse")
b.append("bear")
b.enum()
print a.name
a.enum()

The output...
>>
A:
one
two
B:
one
two
horse
bear
A:
one
two
horse
bear
>>

How do i get:
A:
one
two
B:
horse
bear
A:
one
two

Thanks,

glue

hi,

try this,
class A:
def __init__(self, name):
self.name = name
self.data=[] # Define an array when you
instantiate an object.
def append(self, info):
#self.data=[]
self.data.append(info)
def enum(self):
for x in self.data:
print "\t%s" % x

a = A("A:")
print a.name
a.append("one")
a.append("two")
a.enum()
b = A("B:")
print b.name
b.append("horse")
b.append("bear")
b.enum()
print a.name
a.enum()

Oct 10 '06 #4
glue wrote:
I have a class with a list member and the list seems to behave like
it's static while other class members don't. The code...
*all* class attributes are shared by all instances. however, instance
attributes hide class attributes with the same name.

in your case, you're hiding the "name" class attribute by creating an
instance attribute with the same name in the "__init__" method, but
you're modifying the shared "data" attribute in the "append" method.

if you want separate instances to use separate objects, make sure you
create new objects for each new instance. see Tim's reply for how to
do that.

</F>
class A:
name = ""
data = []
def __init__(self, name):
self.name = name
def append(self, info):
self.data.append(info)
def enum(self):
for x in self.data:
print "\t%s" % x
Oct 10 '06 #5
"glue" <mi**********@gmail.comwrites:
I have a class with a list member and the list seems to behave like
it's static while other class members don't.
It's not "static"; rather, it's a class attribute, by virtue of being
bound when the class is defined. Those are shared by all instances of
the class.
The code...

class A:
name = ""
data = []
This runs when the class is defined, creates two new objects and binds
them to the attribute names "name" and "data". All instances will
share both of these unless they re-bind the names to some other
object.
def __init__(self, name):
self.name = name
This defines a function that runs on initialisation of a new instance
of the class, and re-binds the attribute name "name" to the object
passed as the second parameter to __init__.

The binding that occurred when the class was defined is now
irrelevant. This is known as "shadowing" the class attribute; you've
re-bound the name to a different object.
def append(self, info):
self.data.append(info)
This defines a function that runs when the 'append' method is called,
and asks the existing object bound to the "data" attribute -- still
the one that was bound when the class was defined -- to modify itself
in-place (with its own 'append' method).

--
\ "None can love freedom heartily, but good men; the rest love |
`\ not freedom, but license." -- John Milton |
_o__) |
Ben Finney

Oct 11 '06 #6
Fredrik Lundh wrote:
if you want separate instances to use separate objects, make sure you
create new objects for each new instance. see Tim's reply for how to
do that.
kath's response is probably better.

In Python, you don't define the instance members in the class scope
like the OP has done:
class A:
name = ""
data = []
You define them when you attach them to an instance, e.g.

class A:
def __init__(self):
self.member1 = 'a'

def ThisWorksToo(self):
self.member2 = 'b'

# this also works
a = A()
a.member3 = 'c'

-tom!
Oct 11 '06 #7
Tom Plunket wrote:
>if you want separate instances to use separate objects, make sure you
create new objects for each new instance. see Tim's reply for how to
do that.

kath's response is probably better.
so what's the practical difference between

def __init__(self, name):
self.name = name
self.data = []

and

def __init__(self, name):
self.name = name
self.data=[]

?
In Python, you don't define the instance members in the class scope
like the OP has done:
the OP's approach works perfectly fine, as long as you understand that
class attributes are shared.

</F>

Oct 11 '06 #8
Fredrik Lundh wrote:
so what's the practical difference between

def __init__(self, name):
self.name = name
self.data = []

and

def __init__(self, name):
self.name = name
self.data=[]
Ignoring nerd-extreme-pedantic-mode for this circumstance, you elided
the bits that were functionally different.

IOW, based on the OP's post, it appeared that C++ was infecting their
Python, and removing the class attributes entirely was likely what the
OP actually wanted.
In Python, you don't define the instance members in the class scope
like the OP has done:

the OP's approach works perfectly fine, as long as you understand that
class attributes are shared.
Obviously, as is "sticking a gun in your mouth is perfectly fine, as
long as you understand that pulling the trigger will yield a large
hole in the back of your skull." My reading of the OP's post was that
shared attributes were not desired.

-tom!
Oct 12 '06 #9
Tom Plunket wrote:
Obviously, as is "sticking a gun in your mouth is perfectly fine, as
long as you understand that pulling the trigger will yield a large
hole in the back of your skull."
in my experience, the "you're not old enough to understand this"
approach to teaching usually means that the teacher is immature,
not the student. I prefer to explain how things work. everyone
can understand how Python works. it's pretty simple, actually.

</F>

Oct 12 '06 #10

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

Similar topics

3
by: DanielBradley | last post by:
Hello all, I have recently been porting code from Linux to cygwin and came across a problem with static const class members (discussed below). I am seeking to determine whether I am programming...
8
by: Scott J. McCaughrin | last post by:
The following program compiles fine but elicits this message from the linker: "undefined reference to VarArray::funct" and thus fails. It seems to behave as if the static data-member:...
7
by: Sunny | last post by:
Hi all, According C# Language Specification : 10.11 Static constructors: The static constructor for a class executes at most once in a given application domain. The execution of a static...
14
by: Dave Booker | last post by:
It looks like the language is trying to prevent me from doing this sort of thing. Nevertheless, the following compiles, and I'd like to know why it doesn't work the way it should: public class...
12
by: mast2as | last post by:
Hi everyone... I have a TExceptionHandler class that is uses in the code to thow exceptions. Whenever an exception is thrown the TExceptionHander constructor takes an error code (int) as an...
15
by: Bit byte | last post by:
I am writing a small parser object. I need to store keywords etc in lsts. Because this data is to be shared by all instances of my parser class, I have declared the variable as class variables...
5
by: cmk128 | last post by:
Hi In the following code, when you create a object of class child, parent class (class mother) will hold a reference. But i want every class derived from mother class has this ability without...
5
by: mast2as | last post by:
Hi guys Here's the class I try to compile (see below). By itself when I have a test.cc file for example that creates an object which is an instance of the class SpectralProfile, it compiles...
6
by: chandramohanp | last post by:
Hi I am trying to modify class instance members using reflection. I am having problem when trying to add/remove/display elements related to List<int> member. Following is the code. class...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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...
0
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...

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.