【发布时间】:2020-03-09 21:30:53
【问题描述】:
我有一个班级叫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 的打印语句,它打印出正确的值。但是,如果我尝试在 if 和 for 循环之外调用 s.state_col,则会收到错误消息:
AttributeError Traceback(最近调用 最后)在 ----> 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 设置在循环内或让我在外部调用它?我该如何解决这个问题?
【问题讨论】:
-
在您的情况下,在调用 setter 之前调用 getter 将调用该异常,因为
self._state_col否则不存在,这与有状态编程的概念完全一致。这可以说是一个糟糕的设计选择:您应该要么处理异常,要么避免这种有状态的编程。顺便说一句,所有属性都应该在对象初始化期间声明。您始终可以将None(或任何其他“空”值)分配给未设置的变量并在 getter 中处理这种情况。 -
我对更好的设计有点困惑。我对使用
classes有点陌生,我不确定你在设置器之前调用getter 是什么意思。你能说明一下吗?
标签: python-3.x class initialization getter-setter