简体   繁体   English

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

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

Python class attributes and PHP static class properties at the surface appear to function identically (excluding the ability in PHP to add visibility public/protected/private). 表面上的Python类属性和PHP静态类属性似乎具有相同的功能(不包括PHP中添加公共/受保护/私有可见性的功能)。

Use of either statics or attributes: 使用静态或属性:

  • Are tied to the class not the instance 绑定到类而不是实例
  • Must be evaluated at run time 必须在运行时进行评估
  • if you rely on either inside a class method definition you're going to have difficulty achieving complete coverage for testing of that method. 如果您依靠类方法定义中的任何一个,您将很难获得对该方法的测试的完整介绍。

My question is are there any significant differences I'm missing. 我的问题是我是否缺少任何重大差异。

When looking up python instances for an attribute with the same name as the class variable, it will provide the class variable instead. 在python实例中查找与类变量名称相同的属性时,它将提供类变量。

In PHP... 在PHP中...

class C 
{
    static $foo = 42;
}

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

In Python... 在Python中...

class C:
    foo = 42

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

Even more interesting... 更有趣的是...

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']

In other words, be very careful with class variables in Python. 换句话说,请谨慎使用Python中的类变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM