class MyClass(Object):
def __init__(self, x=None):
if x:
self.x = x
def do_something(self):
print self.x
Now I have two objects
my_class1 = MyClass(x)
my_class2 = MyClass()
I want to use x when this my_class2 object is called
As other languages Support static variable like java,c++ etc.
Assign it as property to the class:
>>> class MyClass(object):
def __init__(self, x=None):
if x is not None:
self.__class__.x = x
def do_something(self):
print self.x # or self.__class__.x, to avoid getting instance property
>>> my_class1 = MyClass('aaa')
>>> my_class2 = MyClass()
>>> my_class2.do_something()
aaa
There are no static variables in Python, but you can use the class variables for that. 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 looks first for instance-level variable, instantiated as self.x
, and if not found - then looks for Class.x
. So you can define it on class level, but override it on instance level.
A widely-used example is to use a default class variable with possible override into 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With