Python 函数和方法的区别

按照惯例,吟诗一首

      苏轼《题西林壁》
横看成岭侧成峰,远近高低各不同。
不识庐山真面目,只缘身在此山中。

学习使用Python有一段时间了,之前也没有怎么在意函数和方法的区别,今天就来扒一扒两者的区别,

开门见山,直奔主题

1、区别

1、函数需要类名去调用,是方法需要类的实例(对象)去调用

2、方法调用是自动传参self,函数调用需要手动传参self

举个例子体会一下:

from types import FunctionType, MethodType


class Person:
    def __init__(self):
        self.name = 'allen'

    def eat(self):
        pass


person = Person()
print(isinstance(person.eat, MethodType))
print(isinstance(person.eat, FunctionType))

print(isinstance(Person.eat, MethodType))
print(isinstance(Person.eat, FunctionType))

结果如下

True
False
False
True
原文地址:https://www.cnblogs.com/suxianglun/p/10879869.html