Let's take this example:
class Foo:
def func(self):
pass
def func():
pass
f1 = Foo.func
f2 = func
I'm inspecting code and want to find out from dir
or inspect
if f1
is a class method and f2
is a function that is not part of any class ?
Built-in inspect module has ismember and isfunction methods, https://docs.python.org/3/library/inspect.html
However, unless you're doing something rather esoteric, it should not matter for user code.
EDIT: And if you are doing something esoteric, note that in the original question you asked about the attribute on a class Foo
, not on an instance of Foo
. And that makes a difference:
In [1]: def f(): return None
In [2]: class F:
...: def f(self):
...: return None
...:
In [3]: import inspect
In [4]: [inspect.isfunction(_) for _ in [f, F.f, F().f]]
Out[4]: [True, True, False]
In [5]: [inspect.ismethod(_) for _ in [f, F.f, F().f]]
Out[5]: [False, False, True]
at this moment the only thing I found is obj.__qualname__
- if it contains a dot - this means it's a method of the class
but I'm not 100% sure this is perfect solution
Just print the function names :
print('f1 =',f1)
print('f2 =',f2)
The output is :
f1 = <function Foo.func at 0x7f56105f3620>
f2 = <function func at 0x7f5611ce7e18>
This gives the full function names, including the parent class name if it is a class method as Foo.func
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.