Python 在另一个类中使用变量

标签 python python-3.x

我是 Python 新手,我想知道:是否可以在另一个类中使用一个变量?

例如:

class Hello:

    def function_a(self):
        x = 1


class World:

    def function_b(self):
        print(x)


a = Hello()
b = World()
a.function_a()
b.function_b()

如何在类(class)之间共享“x”?

最佳答案

事实上,这是做不到的。简单的选项是通过在每个使用它的函数的开头添加 global x 行来使 x 成为全局的。

最佳做法是避免使用全局变量并传递包含共享变量的对象:

class Hello:

    def function_a(self):
        # Stores the x variable in the current instance of Hello
        self.x = 1


class World:

    def function_b(self, a):
        print(a.x)


a = Hello()
b = World()
a.function_a()
b.function_b(a)

关于Python 在另一个类中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38149401/

相关文章:

python - 如何从 qcombobox 获取 itemdata?

python-3.x - 我们如何从 grafana 仪表板中提取数据?

python - 如何将 None 插入列表?

python - 下载特定Python模块时出现问题 'Pip'

python - Bjoern v/s Gunicorn POST 请求

python - 在 Python 中有效比较两个文件中的行

python - 使用 Python codecs.write 编写换行符

python - Snakemake 通过通配符将文件分组在一起

python - 使用循环查找散列对象中前 d 个零的数量

python-3.x - LightGBM 中不平衡数据集的情感分析