Man beachte den kleinen Unterschied zwischen PHP und Python, der mich einige Zeit erstmal gekostet hat:
PHP:
class T {
var $x = array();
}
$a = new T();
array_push($a->x, 1);
echo count($a->x); // <strong>Ausgabe: 1</strong>
$b = new T();
array_push($b->x, 2);
echo count($b->x); // <strong>Ausgabe: 1</strong>
Dagegen ein nahezu äquivalentes Konstrukt in Python:
x = []
a = T()
a.x.append(1)
print len(a.x) # <strong>Ausgabe: 1</strong>
b = T()
b.x.append(2)
print len(b.x) # <strong>Ausgabe: 2</strong>
Die Erklärung findet sich übrigens hier:
Objects have individuality, and multiple names (in multiple scopes) can be bound to the same object. This is known as aliasing in other languages. This is usually not appreciated on a first glance at Python, and can be safely ignored when dealing with immutable basic types (numbers, strings, tuples). However, aliasing has an (intended!) effect on the semantics of Python code involving mutable objects such as lists, dictionaries, and most types representing entities outside the program (files, windows, etc.).