函数与方法的区别

# 函数:就是普通函数,有几个值就要传几个值

# 方法:面向对象是绑定给对象的,类,绑定给谁,谁来调用,会自动传值,谁来调用就会把谁传入,是定义在类中的,其他大体和函数定义差不多,这里需要注意的一点就是方法必须带一个默认参数self(静态方法除外)

# 总结:只要能自动传值的,就是方法,有几个值传几个值的就是函数
def add(a, b):
    return a + b


class Person:
    # 方法:绑定给对象的【不一定是方法】
    def speak(self):
        print('人说话')

    @classmethod
    def test(cls):
        print('类的绑定方法')

    @staticmethod
    def ttt():
        print('static')


p = Person()

from types import MethodType, FunctionType

# 如何确定到底是函数还是方法
from types import MethodType, FunctionType

print(isinstance(add, MethodType))  # False add 是个函数,不是方法
print(isinstance(add, FunctionType))  # True

print(isinstance(p.speak, MethodType))  # 方法
print(isinstance(p.speak, FunctionType))  # 不是函数

print(isinstance(Person.speak, FunctionType))  # 类来调用,它就是普通函数,有几个值就要传几个值
print(isinstance(Person.speak, MethodType))  # 不是方法了

Person.speak(p)  # 普通函数

print(isinstance(Person.test, FunctionType))  # 不是函数
print(isinstance(Person.test, MethodType))  # 类来调用,类的绑定方法

print(isinstance(p.test, FunctionType))  # 不是函数
print(isinstance(p.test, MethodType))  # 对象来调用,类的绑定方法

Person.test()

print(isinstance(p.ttt, FunctionType))  # 静态方法,本质就是个函数,有几个值就要传几个值
print(isinstance(p.ttt, MethodType))

posted @ 2022-12-14 20:09  小张不爱吃泡面  阅读(38)  评论(0编辑  收藏  举报