Python Class 属性与 PHP 静态 class 属性有何不同?

How are Python Class attributes different from PHP static class properties?

Python class 属性和 PHP 静态 class 属性在表面上的功能似乎相同(不包括 PHP 中添加可见性 public/protected/private).

静态或属性的使用:

我的问题是我遗漏了任何显着差异。

当为与 class 变量同名的属性查找 python 个实例时,它将提供 class 变量。

在PHP...

class C 
{
    static $foo = 42;
}

$i = new C();
var_dump($i->foo);  // null, plus a notice

在Python...

class C:
    foo = 42

i = C()
print(i.foo)  # 42

更有趣...

class C:
    foo = []

a = C()
b = C()
c = C()

a.foo = ['hello']
b.foo.append('world')

print(C.foo) # ['world']

print(a.foo) # ['hello']
print(b.foo) # ['world']
print(c.foo) # ['world']

换句话说,在 Python.

中使用 class 个变量要非常小心