python -- 判断函数和方法

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 函数与方法的区别 (前两条重点)
  • 函数:全部都是显性传参(手动传参)

  • 方法:存在隐性传参(自动传参 -- 对象调用类中的方法,自动将对象传给self,类方法)

    函数跟对象无关

    方法可以操作类内部的数据

    方法跟对象是关联的 例如: 字符串的方法中 s.strip()

    Java 中只有方法, C 中只有函数 C++取决于是都在类中

转载于:https://www.cnblogs.com/Agoni-7/p/11202757.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值