装饰器装饰实例函数与普通函数的区别&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")
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")
Note:
需要注意被装饰的实例函数func在装饰器里的type也是function,调用被装饰的实例函数func时,要写成 func(self, args, **kwargs), 而不是self.func( args, **kwargs).
这需要我们先了解python中method和func的区别
使用实例对象引用的实例函数是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)。
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.