对象中通过类或者实例的方法调用方式的不同

如果通过类中取得的方法,需要传入实例

class A(object):
    def test(self, *args):
        print(*args)

if __name__ == '__main__':
    a = A()
    a.test(7, 8, 9)
    # method from class object
    m1 = A.test
    m1(a, 7, 8, 9, 10)
    # method from instance object
    m2 = a.test
    m2(7, 8, 9, 10)

也就是说, 实例方法的第一个参数是实例本身,如果写decorator的时候,要特别注意

比如print_args这个decorator, 需要打印参数,就需要把第一个参数给选出来不作处理


def print_args(func):
    def wrapper(*args):
        _, *rest = args
        print("args: ", *rest)
        func(*args)
    return wrapper

class A(object):

    @print_args
    def test(self, *args):
        print(*args)

if __name__ == '__main__':
    a = A()
    a.test(7, 8, 9)
    # method from class object
    m1 = A.test
    m1(a, 7, 8, 9, 10)
    # method from instance object
    m2 = a.test
    m2(7, 8, 9, 10)