Python:如何在另一个对象中使用第一类对象构造函数值

标签 python

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/

相关文章:

python - 在每个特定时间间隔后训练 ML 模型时的内存使用问题

java - 从 python 执行和捕获 java 执行的输出

javascript - 如何正确处理页面刷新?

python - 在 python matplotlib 中使 Label、bbox 或 axes.text 的边框与 Graph 的脊柱齐平

python - 比较 Conv2D 与 Tensorflow 和 PyTorch 之间的填充

python - 存储映射到字符串的整数以便键可以是 python 中的范围的最佳方法是什么?

python - “QCombination”对象不可迭代

.net - IronPython 与原始 Python 的比较。我对第一个有什么期望?

python - 应用 alembic 迁移后表序列 id 不增加

python - 如何使用方法名分配给变量来动态调用类中的方法