来自Swift我在使用.None类型的Python时遇到了一些困难。如果在数组中找不到我正在寻找的对象,我有一些函数可能会返回None
。
然后我必须按如下方式嵌套我的代码:
varA = self.getVariableByName(Variables.varA)
if varA is None:
varB = self.getVariableByName(Variables.varB)
varC = self.getVariableByName(Variables.varC)
if varB is not None and varC is not None:
# Do something with varB and varC
在Swift中,我曾经能够在if语句中绑定变量
let f = getVariableByName
if f(Variables.varA) == nil, let varB = f(Variables.varB), let varC = f(Variables.varC) {
// Do something with varB and varC
}
什么是处理None
的更'pythonic'方法?
答案 0 :(得分:0)
我认为处理这种情况最好的方法是异常处理。
例如。如果找不到该元素,则使self.getVariableByName
引发异常。然后你可以这样做:
try:
varA = self.getVariableByName(Variables.varA)
except RuntimeError:
varB = self.getVariableByName(Variables.varB)
varC = self.getVariableByName(Variables.varC)
# do something with varB and varC
获取Swift示例的等价物。
如果您不能/不想更改self.getVariableByName
,您可以做的最好的事情是:
f = self.getVariableByName
if f(Variables.varA):
varB, varC = f(Variables.varB), f(Variables.varC)
if not (varB is None or varC is None):
# do something with varB and varC
答案 1 :(得分:-1)
with tempChkStatus (
PMN_CODE, REF_PERIOD , SERVICE_TYPE , STATUS , UPDATED_DTM) as
(
select 'A', '01/2016' ,'OI', 'I', to_date('19/08/2016 10:54:44', 'dd/mm/yyyy hh24:mi:ss') from dual union all
select 'A', '01/2016' ,'OP', 'N', to_date('06/06/2017 15:09:55', 'dd/mm/yyyy hh24:mi:ss') from dual union all
select 'A', '02/2016' ,'OT', 'I', to_date('31/08/2016 08:37:45', 'dd/mm/yyyy hh24:mi:ss') from dual union all
select 'A', '02/2016' ,'OT', 'N', to_date('12/10/2016 11:13:56', 'dd/mm/yyyy hh24:mi:ss') from dual union all
select 'A', '04/2016' ,'OI', 'I', to_date('19/08/2016 10:54:44', 'dd/mm/yyyy hh24:mi:ss') from dual union all
select 'A', '04/2016' ,'OP', 'N', to_date('06/06/2017 15:09:55', 'dd/mm/yyyy hh24:mi:ss') from dual
)
select * from (
select e.*, max(updated_dtm) over (partition by ref_period) md from tempchkstatus e
)
where updated_dtm = md
;
但确定if not hasattr(Variables, 'varA'):
varB = Variables.varB
可能会丢失,因此最好检查是否存在此类属性,或使用默认值varB
或捕获getattr()
例外。