如何在 class 中使用 globals()[]
How to use globals()[] within a class
如果我想像这样调用一个变量:
boolean_0 = True
boolean_1 = False
no = 0
while no < 2:
if globals()[f'boolean_{no}']:
print(f'Boolean {no}', 'is True')
else:
print(f'Boolean {no}', 'is False')
no += 1
如果是这样的class怎么办?
class boolean_func():
def __init__(self):
self.boolean_0 = True
self.boolean_1 = False
def check_status(self):
no = 0
while no < 2:
if globals()[f'boolean_{no}']:
print(f'Boolean {no}', 'is True')
else:
print(f'Boolean {no}', 'is False')
no += 1
尝试使用 self.__dict__
代替:
class boolean_func():
def __init__(self):
self.boolean_0 = True
self.boolean_1 = False
def check_status(self):
no = 0
while no < 2:
if self.__dict__[f'boolean_{no}']:
print(f'Boolean {no}', 'is True')
else:
print(f'Boolean {no}', 'is False')
no += 1
x = boolean_func()
x.check_status()
输出:
Boolean 0 is True
Boolean 1 is False
使用getattr
。这是从对象获取属性的常规方法,并且具有与 class 变量一起使用的优点。
class boolean_func():
def __init__(self):
self.boolean_0 = True
self.boolean_1 = False
def check_status(self):
no = 0
while no < 2:
if getattr(self, f'boolean_{no}'):
print(f'Boolean {no}', 'is True')
else:
print(f'Boolean {no}', 'is False')
no += 1
boolean_func().check_status()
如果我想像这样调用一个变量:
boolean_0 = True
boolean_1 = False
no = 0
while no < 2:
if globals()[f'boolean_{no}']:
print(f'Boolean {no}', 'is True')
else:
print(f'Boolean {no}', 'is False')
no += 1
如果是这样的class怎么办?
class boolean_func():
def __init__(self):
self.boolean_0 = True
self.boolean_1 = False
def check_status(self):
no = 0
while no < 2:
if globals()[f'boolean_{no}']:
print(f'Boolean {no}', 'is True')
else:
print(f'Boolean {no}', 'is False')
no += 1
尝试使用 self.__dict__
代替:
class boolean_func():
def __init__(self):
self.boolean_0 = True
self.boolean_1 = False
def check_status(self):
no = 0
while no < 2:
if self.__dict__[f'boolean_{no}']:
print(f'Boolean {no}', 'is True')
else:
print(f'Boolean {no}', 'is False')
no += 1
x = boolean_func()
x.check_status()
输出:
Boolean 0 is True
Boolean 1 is False
使用getattr
。这是从对象获取属性的常规方法,并且具有与 class 变量一起使用的优点。
class boolean_func():
def __init__(self):
self.boolean_0 = True
self.boolean_1 = False
def check_status(self):
no = 0
while no < 2:
if getattr(self, f'boolean_{no}'):
print(f'Boolean {no}', 'is True')
else:
print(f'Boolean {no}', 'is False')
no += 1
boolean_func().check_status()