如何在我的 class 中使变量成为全局变量,但仅在 class 中使它成为全局变量?

How do I make a variable in my class global but only make it global within the class?

我想使 x 仅在 class.

中是全局的

我试过使用 self.x 但似乎不起作用。不过我可能做错了。

class Test:

   def __init__(self):
      pass

   def test1(self,number):
      global x
      x = number
      print(x)

   def whereIwantToRedefineIt(self):
      print(x)


Test().test1(2) #<------ Making output 2

x=200 #<-------------- It should not be able to redefine the variable

Test().whereIwantToRedefineIt() #<-------- I want to make this output 2

我想让函数 "whereIwantToRedefineIt" 不受 class 之外的 "x=200" 的影响。我希望它输出 2

class Test:

  def __init__(self):
      self.x = None
  def test1(self,number):
      self.x = number
      print(x)

   def whereIwantToRedefineIt(self):
      print(self.x)

如果在同一个实例上调用这些方法,您可以获得想要的结果。

test = Test()
test.test1(2)
test.whereIwantToRedefineIt() # This will print 2

最接近的是 class variable,可以通过在变量名前加上 class 名称来访问它:

class MyClass:
    somevar = 0
    def somemethod(self):
        print(MyClass.somevar)