AttributeError:<Class>对象在循环外没有属性?

时间:2019-11-14 01:25:23

标签: python-3.x class initialization getter-setter

我有一个叫state_class的班级:

class state_class:
  def __init__(self, state_name): 

    self.state_name = state_name

    @property
    def state_col(self):
        """state_col getter"""
        return self._state_col

    @state_col.setter
    def state_col(self):
        """state_col setter"""
        self._state_col = state_col

我在if语句和for循环内初始化此类:

for region in regions:
  if region == '1':
    for region in regions:
        for col in range(prelim_sheet.ncols):
          if (prelim_sheet.cell_value(0, col) == r.region_name):
           ...
          else:
            for state in state_list:
                if state.strip() == 'NewHampshire':  
                    s = state_class(state)
                    if ((prelim_sheet.cell_value(0, col)).replace(" ", "") == s.state_name):
                        s.state_col = col
                        print(s.state_col)
                        ...

如您所见,在底部,我有一个s.state_col的打印语句,它打印出正确的值。但是,如果我尝试在s.state_colif循环之外调用for,则会收到错误消息:

  

AttributeError跟踪(最近的调用)   最后)   ----> 1 s.state_col

     

AttributeError:“ state_class”对象没有属性“ state_col”

我已经在循环外对此进行了测试,并且效果很好:

s = state_class('NewHampshire')
col = 20
s.state_col = col
print(s.state)
>>> 20

是否有理由将state_col设置在循环内,或者让我在循环外调用它?我该如何解决?

2 个答案:

答案 0 :(得分:1)

正如@Eli Korvigo所说,您应该在类的 init 函数中初始化所有变量,否则在设置变量之前它们不存在。

编辑:

我靠近您的代码,缩进不正确,setter函数需要输入。不太重要的是,类名称应为CamelCase。该代码现在应该可以工作:

class StateClass:
    def __init__(self, state_name):
        self.state_name = state_name
        self._state_col = None

    @property
    def state_col(self):
        """state_col getter"""
        return self._state_col

    @state_col.setter
    def state_col(self, s):
        """state_col setter"""
        self._state_col = s

答案 1 :(得分:0)

经过反复尝试,我确定此问题的症结不在state_class getter和setter中(它们在循环内工作),而是我在末尾的else语句中

for col in range(prelim_sheet.ncols):
    if (prelim_sheet.cell_value(0, col) == r.region_name):
       ...
    else:
        for state in state_list:
            if state.strip() == 'NewHampshire':  
                s = state_class(state)
                if ((prelim_sheet.cell_value(0, col)).replace(" ", "") == s.state_name):
                    s.state_col = col
                    print(s.state_col)

从本质上讲,这就是说,如果不满足第一个条件,则继续滚动cols(大约有34列),并且类实例化在此过程中变得混乱。 为了解决这个问题,我添加了一些内容。 1)我更改了else' to an elif`语句并设置了一些条件。 2)我添加了一个动态字典,该字典将允许我为每个州存储该类的实例(使用“ NewHampshire”仅用于测试目的)。尽管我认为@big_bad_bison的解决方案可能会起作用(我赞扬他们),但实际上,在这种情况下,我的新解决方案最适合我。感谢您的协助:

    state_map = {}
    for col in range(prelim_sheet.ncols):
        col_name = prelim_sheet.cell_value(0, col)

        if (col_name == region_map[region].region_name):
            region_map[region].region_total_col = col
            region_map[region].detailed_col = region_map[region].region_total_col
            region_map[region].approx_col = region_map[region].region_total_col + 1
            region_map[region].unmapped_col = region_map[region].region_total_col + 2
            region_map[region].total_col = region_map[region].region_total_col + 3


        elif (col_name.replace(" ", "") in region_map[region].region_long_list):
            state = col_name
            state_map[state] = state_class(state)
            state_map[state].state_col = col
            state_map[state].detailed_col = state_map[state].state_col
            state_map[state].approx_col = state_map[state].state_col + 1
            state_map[state].unmapped_col = state_map[state].state_col + 2
            state_map[state].total_col = state_map[state].state_col + 3    
            print("The col is {}".format(str(col)),state_map[state].state_col, state)

        region_map[region].state_map = state_map