There are no static variables in Python, but you can use class variables for this. Here is an example:
class MyClass(object): x = 0 def __init__(self, x=None): if x: MyClass.x = x def do_something(self): print "x:", self.x c1 = MyClass() c1.do_something() >> x: 0 c2 = MyClass(10) c2.do_something() >> x: 10 c3 = MyClass() c3.do_something() >> x: 10
When you call self.x
, it first looks for the instance level variable created as self.x
, and if it is not found, it looks for Class.x
. That way you can define it at the class level, but override it at the instance level.
A widely used example is the use of a default class variable with possible overriding into an instance:
class MyClass(object): x = 0 def __init__(self, x=None): self.x = x or MyClass.x def do_something(self): print "x:", self.x c1 = MyClass() c1.do_something() >> x: 0 c2 = MyClass(10) c2.do_something() >> x: 10 c3 = MyClass() c3.do_something() >> x: 0
Tisho source share