I’m new to python, and it really confused me.
I want to write something like
class line :
points = []
def add(self, point) :
self.points.append(point)
line1 = line()
line2 = line()
line1.add("Some point")
print line2.points
Output: ['Some point']
And the result is like they refers to the same list.
But I do want a object member not a class member.
And I tried, if points is int, or some other simple type it works fine.
Besides, I know if I write
def __init__(self) :
self.points = []
it will also work, but I don’t get why they are pointing to same list by default.
ps. I know writing a init will work.
class line :
name = "abc"
def changename(self, name) :
self.name = name
line1 = line()
line2 = line()
line1.changename(123)
print line2.name
But the code above output "abc"
So I don’t understand why same kind of declaration act different by type.
Because in this case
pointsis a class member. It belongs to the class, and sinceline1andline2are of the same class,pointsis the same list.So you are right in using
instead to create an instance member which is tied to the instance, not the class.
To answer your edit
If you write:
you override your class member and create a new instance member using
self.name = name.To get back to your first example, it would be like writing: