如何在 class 的同一实例中的另一个 def 中访问在 __init__ 中创建的变量?
How to access variables created in __init__ in another def in the same instance of a class?
目标:能够在 play
.
访问 a
注意:我需要在 class 的同一个实例中通过变量保存信息,因为 play
将被多次调用。
代码:
class something():
def __init__(self):
a = 2
def play(self, b):
return True if a == b else False
test = something()
print(test.play(1))
预期:它应该 print False
因为 2 != 1
,但我得到了这个错误:
UnboundLocalError: local variable 'a' referenced before assignment
我试过:
- 摆脱
__init__
并将 int 放在 def 之外。
- 在
__init__
之前设置 int 并在 __init__
中访问它。
注意:在创建 class 的新实例时,我无法将参数传递给 __init__
,这是为了练习,可以在 here 中找到,我不控制新实例的创建。
class something():
def __init__(self):
self.a = 2
def play(self, b):
return True if self.a == b else False
test = something()
print(test.play(1))
在 __init__
中你必须使用 self.variable
并且同样可以用于相同 class 的其他功能。
目标:能够在 play
.
a
注意:我需要在 class 的同一个实例中通过变量保存信息,因为 play
将被多次调用。
代码:
class something():
def __init__(self):
a = 2
def play(self, b):
return True if a == b else False
test = something()
print(test.play(1))
预期:它应该 print False
因为 2 != 1
,但我得到了这个错误:
UnboundLocalError: local variable 'a' referenced before assignment
我试过:
- 摆脱
__init__
并将 int 放在 def 之外。 - 在
__init__
之前设置 int 并在__init__
中访问它。
注意:在创建 class 的新实例时,我无法将参数传递给 __init__
,这是为了练习,可以在 here 中找到,我不控制新实例的创建。
class something():
def __init__(self):
self.a = 2
def play(self, b):
return True if self.a == b else False
test = something()
print(test.play(1))
在 __init__
中你必须使用 self.variable
并且同样可以用于相同 class 的其他功能。