Der kleine Unterschied

Man beachte den kleinen Unterschied zwischen PHP und Python, der mich einige Zeit erstmal gekostet hat:


class T {
    var $x = array();
$a = new T();
array_push($a->x, 1);
echo count($a-&gt;x); // <strong>Ausgabe: 1</strong>
$b = new T();
array_push($b-&gt;x, 2);
echo count($b-&gt;x); // <strong>Ausgabe: 1</strong>

Dagegen ein nahezu äquivalentes Konstrukt in Python:

class T:
&nbsp;&nbsp;&nbsp;&nbsp;x = []
a = T()
print len(a.x) # <strong>Ausgabe: 1</strong>
b = T()
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.).