Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

怎么判断一个函数是对象的方法?

>>> f = open("test.ss", "r")
>>> type(f.read)
<class 'builtin_function_or_method'>

type函数能得到某个变量的类型,怎么确定一个变量是某个对象的方法呢?注意,是确定是对象的方法而不是全局函数,这是有区别的!

我写出了如下程序片段,但是结果都不对。

import types

if type(x) == types.BuiltinFunctionType or type(x) == types.BuiltinMethodType :

正确的写法是什么?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

对于Python代码定义的类和函数,可以通过types.MethodType和types.FunctionType判断。而且只能分辨出对象实例的绑定方法。

import types

# function
isinstance(A.f, types.FunctionType)  # True

# method
isinstance(A().f, types.MethodType)  # True

但是对builtin类型的对象不能判断是方法还是函数。

这里说的builtin是指用C/C++编写的二进制模块,对于二进制模块提供的函数来说没有方法和函数的区别。这个是 Python C-API 决定的。

在标准库里提供的 types.BuiltinMethodTypetypes.BuiltinFunctionType 是一样的。

types.BuiltinMethodType is types.BuiltinFunctionType  # True

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...