class MyClass(Object):
def __init__(self, x=None):
if x:
self.x = x
def do_something(self):
print self.x
现在我有两个对象
my_class1 = MyClass(x)
my_class2 = MyClass()
我想在调用这个 my_class2 对象时使用 x
由于其他语言支持静态变量,如java、c++等。
最佳答案
将其作为属性分配给类:
>>> 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
关于Python:如何在另一个对象中使用第一类对象构造函数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11687130/