相关疑难解决方法(0)

为什么inspect.ismethod和inspect.isfunction从python 2 - > 3之间有区别?

所以这段代码:

from inspect import *

class X(object):
  def y(self):
    pass

methods = getmembers(X, predicate=ismethod)
functions = getmembers(X, predicate=isfunction)

print("%r" % methods)
print("%r" % functions)
Run Code Online (Sandbox Code Playgroud)

从python2.7产生:

[('y', <unbound method X.y>)]
[]
Run Code Online (Sandbox Code Playgroud)

并从python3.3产生:

[]
[('y', <function X.y at 0x1006ee3b0>)]
Run Code Online (Sandbox Code Playgroud)

我已经四处寻找,但我看不出任何明显的行为改变的原因.

具体来说,为什么python 3将我的方法视为一个函数?

是否有任何跨运行时方式获取类的方法列表?

(即在python2.X和3.X上运行时返回相同内容的东西)

编辑:getmembers()示例不起作用:

from inspect import *

class X(object):
  def y(self):
    pass

methods = getmembers(X)
for i in methods:
  if ismethod(i):
    print("Method: %s" % str(i))
  else:
    print("Not a method: %s" % str(i))
Run Code Online (Sandbox Code Playgroud)

打印:

Not a method: ('__class__', <attribute '__class__' of …
Run Code Online (Sandbox Code Playgroud)

python

18
推荐指数
2
解决办法
4427
查看次数

为类添加装饰器 通过装饰类为类的方法添加装饰器

我正在尝试创建一个可以在类上定义的装饰器,并装饰其中定义的所有内容。首先让我展示一下我已经基于其他 SO 答案得到的设置:

import inspect


# https://stackoverflow.com/a/18421294/577669
def log(func):
    def wrapped(*args, **kwargs):
        try:
            print("Entering: [%s]" % func)
            try:
                # https://stackoverflow.com/questions/19227724/check-if-a-function-uses-classmethod
                if inspect.ismethod(func) and func.__self__:  # class method
                    return func(*args[1:], **kwargs)
                if inspect.isdatadescriptor(func):
                    return func.fget(args[0])
                return func(*args, **kwargs)
            except Exception as e:
                print('Exception in %s : (%s) %s' % (func, e.__class__.__name__, e))
        finally:
            print("Exiting: [%s]" % func)
    return wrapped


class trace(object):
    def __call__(self, cls):  # instance, owner):
        for name, m in inspect.getmembers(cls, lambda x: inspect.ismethod(x) or inspect.isfunction(x)):
            setattr(cls, name, log(m))
        for …
Run Code Online (Sandbox Code Playgroud)

python decorator

6
推荐指数
1
解决办法
154
查看次数

标签 统计

python ×2

decorator ×1