7.7.1 经过打印函数(方法)名肯定
def func(): pass print(func) # <function func at 0x00000260A2E690D0> class A: def func(self): pass print(A.func) # <function A.func at 0x0000026E65AE9C80> obj = A() print(obj.func) # <bound method A.func of <__main__.A object at 0x00000230BAD4C9E8>>
7.7.2 经过types模块验证
- 类名调用类中的方法,是一个函数
- 对象调用类中的方法,是一个方法
from types import FunctionType from types import MethodType def Foo(): pass class A: def func(self): pass obj = A() print(isinstance(Foo,FunctionType)) # True print(isinstance(A.func,FunctionType)) # True print(isinstance(A.func,MethodType) # False print(isinstance(obj.func,FunctionType)) # False print(isinstance(obj.func,MethodType)) # True
7.7.3 静态方法是函数
- 类名和对象调用都是函数
- 类方法:类名和对象调用都是方法
from types import FunctionType from types import MethodType class A: def func(self): pass @classmethod def func1(self): pass @staticmethod def func2(self): pass obj = A() # 静态方法实际上是函数 print(isinstance(A.func2,FunctionType)) # True print(isinstance(obj.func2,FunctionType)) # True
7.7.4 函数与方法的区别 (前两条重点)
-
函数:所有都是显性传参(手动传参)python
-
方法:存在隐性传参(自动传参 -- 对象调用类中的方法,自动将对象传给self,类方法)函数
函数跟对象无关spa
方法能够操做类内部的数据code
方法跟对象是关联的 例如: 字符串的方法中 s.strip()对象
Java 中只有方法, C 中只有函数 C++取决因而都在类中ip