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

kath nitte.sudhir at gmail.com
Tue Oct 10 14:48:56 EDT 2006


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()




More information about the Python-list mailing list