[英]How do I make a variable in my class global but only make it global within the class?
我想做到这一点,所以x仅在类中是全局的。
我尝试使用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”不受类外部的“ 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 MyClass:
somevar = 0
def somemethod(self):
print(MyClass.somevar)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.