Python 2.7 如何直接检查getattr widhout hasattr中是否存在方法
使用hasattr()检查此对象中是否存在方法 但是如何在if中的getattr()中直接访问并检查if费用:Python 2.7 如何直接检查getattr widhout hasattr中是否存在方法,python-2.7,Python 2.7,使用hasattr()检查此对象中是否存在方法 但是如何在if中的getattr()中直接访问并检查if费用: if hasattr(acquirer, custom_method_name): fees = getattr(acquirer, custom_method_name)(values.get('amount', 0.0)) values['fees'] = float_round(fees, 2) 我认为删除hasattr检查没有意义。它使您的代码更加稳定。我还建
if hasattr(acquirer, custom_method_name):
fees = getattr(acquirer, custom_method_name)(values.get('amount', 0.0))
values['fees'] = float_round(fees, 2)
我认为删除hasattr检查没有意义。它使您的代码更加稳定。我还建议检查它是否可调用。但是,如果您出于某种原因(可读性?)想这样做,可以通过以下几种方式:
# if python < 3, for 'print' statement to work with 'lambda'
from __future__ import print_function
class RightObject(object):
def __init__(self, text):
self.text = text
def required_method(self):
print('executing %s' % self.text)
class WrongObject(object):
pass
def exec_if_possible(instance, method):
""" This function checks for attribute and if it's a function. """
if hasattr(instance, method):
res_func = getattr(instance, method)
if callable(res_func): # is it a function or not?
res_func()
else:
print('it is not a function')
else:
print('bad object')
def try_exec(instance, method):
""" This is a straight-forward function. """
try:
res_func = getattr(instance, method)()
except AttributeError as at_er:
print(at_er)
except TypeError as ty_er:
print(ty_er)
right = RightObject('right one')
wrong = WrongObject()
func = 'required_method'
# This will work:
exec_if_possible(right, func)
# This will fail as expected:
exec_if_possible(right, 'text')
exec_if_possible(wrong, func)
# The same here:
try_exec(right, func)
try_exec(right, 'text')
try_exec(wrong, func)
# creating a simple crash informer:
default_func = lambda: print('default function')
# one liners, but it is not recommended to use them:
getattr(right, func, default_func)()
getattr(wrong, func, default_func)()
我不清楚你在问什么。是否正在查找
getattr
的可选第三个参数,如果属性不存在,该参数将提供默认值?或者,您是否希望编写“请求原谅比允许更容易”样式的代码,在不首先使用hasattr
的情况下调用getattr
,并捕获您收到的任何AttributeError
?还是你想要别的?
# exec_if_possible():
executing right one
it is not a function
bad object
# try_exec():
executing right one
'str' object is not callable
'WrongObject' object has no attribute 'required_method'
# one-liners:
executing right one
default function