0
votes

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).

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.

1

1 Answers

1
votes

When looking up python instances for an attribute with the same name as the class variable, it will provide the class variable instead.

In PHP...

class C 
{
    static $foo = 42;
}

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

In 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.