我想知道,在将变量与硬编码值进行比较时,如何创建一个程序来检测代码中的以下情况,而不是动态地使用枚举?你知道吗
class AccountType:
BBAN = '000'
IBAN = '001'
UBAN = '002'
LBAN = '003'
我希望代码在以下情况下报告(在日志中放置警告):
payee_account_type = self.get_payee_account_type(rc) # '001' for ex.
if payee_account_type in ('001', '002'): # Report on unsafe lookup
print 'okay, but not sure about the codes, man'
鼓励人们使用以下方法:
payee_account_type = self.get_payee_account_type(rc)
if payee_account_type in (AccountType.IBAN, AccountType.UBAN):
print 'do this for sure'
这样更安全。你知道吗
验证如下==
和!=
检查不是问题:
if payee_account_type == '001':
print 'codes again'
通过将payee_account_type
包装到类中,实现以下__eq__
:
class Variant:
def __init__(self, value):
self._value = value
def get_value(self):
return self._value
class AccountType:
BBAN = Variant('000')
IBAN = Variant('001')
UBAN = Variant('002')
LBAN = Variant('003')
class AccountTypeWrapper(object):
def __init__(self, account_type):
self._account_type = account_type
def __eq__(self, other):
if isinstance(other, Variant):
# Safe usage
return self._account_type == other.get_value()
# The value is hardcoded
log.warning('Unsafe comparison. Use proper enumeration object')
return self._account_type == other
但是如何处理元组查找呢?你知道吗
我知道,我可以创建一个包装查找的约定方法,在这里可以执行检查:
if IbanUtils.account_type_in(account_type, AccountType.IBAN, AccountType.UBAN):
pass
class IbanUtils(object):
def account_type_in(self, account_type, *types_to_check):
for type in types_to_check:
if not isinstance(type, Variant):
log.warning('Unsafe usage')
return account_type in types_to_check
但这不是我的选择,因为我有很多遗留代码我不能接触,但仍然需要报告。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐