使用setattr触发TypeError: an integer is required错误的求助
问题:使用setattr时触发TypeError: an integer is required
我在执行代码中的setattr方法时遇到了TypeError: an integer is required错误,循环第一次迭代就触发了该问题,当时的参数状态为:
attr = 'enable_adjacent_channel' attr_val = True
代码进入布尔类型处理分支,尝试执行setattr(self, attr, bool(config[self.section_name][attr])),但即便config中对应的值已经是布尔类型,解释器仍抛出了上述错误。
涉及的变量
attr_list = ['enable_adjacent_channel', 'enable_cochannel', 'imt_link', 'is_space_to_earth', 'num_snapshots', 'output_dir', 'output_dir_prefix', 'overwrite_output', 'seed', 'system'] config = {'general': {'num_snapshots': 100, 'imt_link': 'DOWNLINK', 'system': 'FSS_SS', 'enable_cochannel': False, 'enable_adjacent_channel': True, 'seed': 101, 'overwrite_output': True}...} self = ParametersGeneral(section_name='general', is_space_to_earth=False, num_snapshots=10000, imt_link='DOWNLINK', system='RAS', enable_cochannel=False, enable_adjacent_channel=True, seed=101, overwrite_output=True, output_dir='output', output_dir_prefix='output')
相关代码
for attr in attr_list: try: attr_val = getattr(self, attr) if isinstance(attr_val, str): setattr(self, attr, config[self.section_name][attr]) elif isinstance(attr_val, bool): setattr(self, attr, bool(config[self.section_name][attr])) elif isinstance(attr_val, float): setattr(self, attr, float(config[self.section_name][attr])) elif isinstance(attr_val, int): setattr(self, attr, int(config[self.section_name][attr])) elif isinstance(attr_val, tuple): # Check if the string defines a list of floats try: param_val = config[self.section_name][attr] tmp_val = list(map(float, param_val.split(","))) setattr(self, attr, tuple(tmp_val)) except ValueError: # its a regular string. Let the specific class implementation # do the sanity check print(f"ParametersBase: could not convert string to tuple \"{self.section_name}.{attr}\"") exit() except KeyError: print(f"ParametersBase: NOTICE! Configuration parameter \"{self.section_name}.{attr}\" is not set in configuration file. Using default value {attr_val}") except Exception as e: print(f"Um erro desconhecido foi encontrado: {e}")
原因分析
这个错误并非来自bool()转换本身,核心原因大概率是:
ParametersGeneral类中enable_adjacent_channel属性被定义为仅接受整数的类型(比如自定义的描述符、重写的__setattr__方法,或者严格类型校验的属性),即便Python中bool是int的子类,这类自定义逻辑仍会拒绝布尔值赋值。- 少数情况是
config[self.section_name][attr]的实际类型并非布尔,而是字符串(比如"True"),但你确认值是布尔类型,所以前者的可能性更高。
解决方案
- 直接赋值,跳过无意义的bool转换:既然
config中的值已经是布尔类型,无需额外转换,直接赋值即可:elif isinstance(attr_val, bool): setattr(self, attr, config[self.section_name][attr]) - 适配整数类型的属性限制:如果类属性确实只接受整数,将布尔值转为对应的整数(1代表True,0代表False):
elif isinstance(attr_val, bool): setattr(self, attr, int(config[self.section_name][attr])) - 检查类属性定义:查看
ParametersGeneral类中enable_adjacent_channel的实现逻辑,确认是否有特殊的赋值限制,必要时调整类的类型校验规则。
内容的提问来源于stack exchange,提问作者joaocabeca
相关产品推荐
相关产品推荐

