from dataclasses import dataclass @dataclass class A: def print(self): x.append(2) print(x) @dataclass class B: def print(self): print(x) x = [1] kwargs = {} a = A(**kwargs) b = B(**kwargs) a.print() b.print()
输出:[1, 2]
[1, 2]
from dataclasses import dataclass @dataclass class A: global x x = 3 def print(self): self.x = 2 print(x) @dataclass class B: def print(self): print(x) x = 1 kwargs = {} a = A(**kwargs) b = B(**kwargs) a.print() b.print()
输出:1
1
from dataclasses import dataclass @dataclass class A: def print(self): global x x = 2 print(x) @dataclass class B: def print(self): print(x) x = 1 kwargs = {} a = A(**kwargs) b = B(**kwargs) a.print() b.print()
输出:2
2
以上测例都属于同一文件,跨文件传递变量,请搜索‘python 跨文件 全局 变量’