Python的函数和方法如何区分呢?

结论>>>:无论是函数还是方法都用def关键字来定义
方法:只要是自动传值都是方法、由谁来调用、会把自身传入
函数:有几个值就传几个值否则会报错

一、详细介绍函数和方法

1. 函数
Python中的函数其实就是我们没有学面向对象编程之前一直在用的编程思想
有几个参数就要传几个参数,否则会报错
2. 方法
绑定给类的方法:对象可以调用,会自动把类传入
绑定给对象的方法:类可调用但是会变成普通函数

二、用几个关键字来判断

MethodType    # 判断检查对象是不是方法
FunctionType  # 判断检查对象是不是函数
isinstance    # 判断检查对象是不是一个类的对象
issubclass    # 判断检查对象是不是另一个类的子类

三、通过代码小案例验证

from types import MethodType, FunctionType


# 名字为Foo的类
class Foo(object):
    # 绑定给对象的方法
    def fetch(self):
        pass

    # 绑定给类的方法
    @classmethod
    def test(cls):
        pass

    # 绑定给类的静态方法
    @staticmethod
    def test1():
        pass


# 类名加括号实例化对象
obj = Foo()


# 普通函数
def add():
    pass


print(isinstance(Foo.fetch, MethodType))  # False  类来调用对象的绑定方法,该方法就变成了普通函数
print(isinstance(obj.fetch, MethodType))  # True   对象来调用自己的绑定方法,fetch就是方法
print(isinstance(Foo.fetch, FunctionType))  # True   类来调用对象的绑定方法,该方法就变成了普通函数
print(isinstance(add, FunctionType))  # True   就是个普通函数
print(isinstance(add, MethodType))  # False  就是个普通函数
print(isinstance(Foo.test, MethodType))  # True   test 是绑定给类的方法,类来调用,就是方法
print(isinstance(obj.test, MethodType))  # True   对象调用类的绑定方法,还是方法
print(isinstance(Foo.test1, MethodType))  # False  是普通函数
print(isinstance(obj.test1, MethodType))  # False  是普通函数
print(isinstance(obj.test1, FunctionType))  # True   静态方法,就是普通函数,对象和类都可以调用,有几个值就传几个值

posted @ 2023-04-06 14:26  阿丽米热  阅读(117)  评论(0编辑  收藏  举报
Title