开发者社区 问答 正文

Python中如何判断是函数还是方法?

Python中如何判断是函数还是方法?

展开
收起
真的很搞笑 2021-11-04 21:45:10 323 分享 版权
1 条回答
写回答
取消 提交回答
  • 什么是函数?什么是方法?

    		def func():
    			pass
    
    
    		class Foo(object):
    
    			def func(self):
    				pass
    
    		# 执行方式一
    		# obj = Foo()
    		# obj.func() # 方法
    
    		# 执行方式二
    		# Foo.func(123) # 函数
    
    		from types import FunctionType,MethodType
    
    		# obj = Foo()
    		# print(isinstance(obj.func,FunctionType)) # False
    		# print(isinstance(obj.func,MethodType))   # True
    
    
    		print(isinstance(Foo.func,FunctionType)) # True
    		print(isinstance(Foo.func,MethodType))   # False
    
    2021-11-04 21:45:32
    赞同 展开评论