相关疑难解决方法(0)

Python装饰器让函数忘记它属于一个类

我正在尝试编写一个装饰器来做日志记录:

def logger(myFunc):
    def new(*args, **keyargs):
        print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__)
        return myFunc(*args, **keyargs)

    return new

class C(object):
    @logger
    def f():
        pass

C().f()
Run Code Online (Sandbox Code Playgroud)

我想要打印:

Entering C.f
Run Code Online (Sandbox Code Playgroud)

但我收到此错误消息:

AttributeError: 'function' object has no attribute 'im_class'
Run Code Online (Sandbox Code Playgroud)

据推测,这与'logger'中'myFunc'的范围有关,但我不知道是什么.

python reflection metaprogramming

59
推荐指数
6
解决办法
2万
查看次数

如果我只知道python中的绑定方法,如何获取类的名称?

在pyton代码中,我有一个对象的绑定方法.只知道这个绑定方法我想知道该对象的类是什么.可能吗?

这是示例代码:

>>> class x:
...     def method(self):
...             pass
...
>>> x
<class __main__.x at 0xb737d1ac> 
>>> x_instance = x()
>>> x_instance
<__main__.x instance at 0xb737c7cc>
>>> boundmethod = x_instance.method
>>> boundmethod
<bound method x.method of <__main__.x instance at 0xb737c7cc>>
>>> str(boundmethod)
'<bound method x.method of <__main__.x instance at 0xb737c7cc>>'
Run Code Online (Sandbox Code Playgroud)

我们假设我只知道boundmethod.如何判断该类是x什么?

python oop classname

3
推荐指数
1
解决办法
1123
查看次数

标签 统计

python ×2

classname ×1

metaprogramming ×1

oop ×1

reflection ×1