装饰器装饰实例函数与普通函数的区别&Python function type和method type的区别

装饰器装饰实例函数与普通函数的区别&Python function type和method type的区别

Note: 文章内容都是基于自己的理解,如有理解错误,欢迎指正修改,大家一起进步。

装饰器装饰普通函数

def my_decorator(func):
    print(func)
    print(type(func))
    def wrapper(*args,  **kwargs):
        print("Something is happening before the instance method is called.")
        result = func(*args, **kwargs)
        print("Something is happening after the instance method is called.")
        return result
    return wrapper

@my_decorator
def my_method(greeting):
    print(f"{greeting}")

my_method("greeting")

在这里插入图片描述

图1

Note: 需要注意当被装饰器装饰的是普通函数时,其type是function,调用这个普通函数func时,直接写成 func(*args, **kwargs)就可以.

装饰器装饰实例函数

def my_decorator(func):
    print(func)
    print(type(func))
    def wrapper(self,*args,  **kwargs):
        print("Something is happening before the instance method is called.")
        result = func(self,*args, **kwargs)
        print("Something is happening after the instance method is called.")
        return result
    return wrapper

class MyClass:
    def __init__(self, name):
        self.name = name

    @my_decorator
    def my_method(self, greeting):
        print(f"{greeting}, {self.name}!")

obj = MyClass("Alice")
obj.my_method("greeting")

在这里插入图片描述

图2

Note:
需要注意被装饰的实例函数func在装饰器里的type也是function,调用被装饰的实例函数func时,要写成 func(self, args, **kwargs), 而不是self.func( args, **kwargs).
这需要我们先了解
pythonmethodfunc的区别

使用实例对象引用的实例函数是method type, 调用方式self.my_method(arg1,arg2). self会通过隐式调用将self作为第一个参数传递

而使用类名引用的实例函数是function type,调用方式是 MyClass.my_method(self,arg1,arg2),需要显式的将self作为第一个参数传递,再传递其它函数

obj是MyClass的实例对象,MyClass是自定义的类
self.my_method 是method type. 调用例子obj.my_method("greeting”)
MyClass.my_method 是funcion type, 调用例子 MyClass.my_method(obj, “greeting”)

因为装饰函数装饰的函数是 function type(如图2所示),所以可以将被装饰函数func看成MyClass.my_method。 在装饰器里调用实例函数my_method,就可以将func(self,arg1,arg2) 等价于 MyClass.my_method(obj,arg1,arg2)。

在这里插入图片描述

图3

GPT对 method 和 function type 区别的解释

Function
A function is a block of code that is defined outside of any class and can perform a specific task when called. Functions can take input arguments and can return values. They are defined using the def keyword. Functions are not associated with any object or class by default, although they can interact with them. Functions can be used for a wide range of tasks, from performing a calculation to processing input data.
Example of a function:

def add_numbers(a, b):
    return a + b

result = add_numbers(5, 3)
print(result)  # Output: 8

Method
A method, on the other hand, is a function that is associated with an object of a class. Methods are defined within a class definition, and they implicitly work on instances of that class by taking the instance as the first parameter, conventionally named self. Methods can access and modify the state of an instance (its attributes) and call other methods of the same object.

Example of a method:
class Calculator:
    def __init__(self, value=0):
        self.value = value
        
    def add(self, amount):
        self.value += amount
        return self.value

calc = Calculator()
result = calc.add(8)
print(result)  
# Output: 8

Key Differences

  • Association: Functions are defined independently of any class, whereas methods are defined within a class and are associated with instances of that class.
  • Call Context: A function can be called by its name directly in the scope where it is defined. A method is called on a specific object, which is implicitly passed to the method as its first argument (self).
  • Usage: Functions are used for tasks that might not require accessing or modifying the properties of a class. Methods are specifically used to interact with object state or perform tasks that are (in some way) related to the object.

Summary

  • A function is a standalone block of code designed to perform a specific task, called independently of objects.
  • A method is a function that is associated with an object of a class, designed to operate with the context of that object.
  • 28
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值