如何检查方法直接存在于getattr widhout hasattr中

时间:2015-05-22 06:56:19

标签: python-2.7

使用hasattr()

检查此对象中是否存在方法

但是如何在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)

1 个答案:

答案 0 :(得分:0)

我认为删除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)()

输出:

# 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