如何使用\u getattr访问调用参数和参数__

2024-10-02 00:28:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的代码,其中大多数代码看起来很笨拙、令人困惑和/或是间接的,但大多数代码都是为了演示我有问题的更大代码的部分。请仔细阅读

# The following part is just to demonstrate the behavior AND CANNOT BE CHANGED UNDER NO CIRCUMSTANCES
# Just define something so you can access something like derived.obj.foo(x)
class Basic(object):
    def foo(self, x=10):
        return x*x

class Derived(object):
    def info(self, x):
        return "Info of Derived: "+str(x) 
    def set(self, obj):
        self.obj = obj

# The following piece of code might be changed, but I would rather not
class DeviceProxy(object):
    def __init__(self):
        # just to set up something that somewhat behaves as the real code in question
        self.proxy = Derived()
        self.proxy.set(Basic())

    # crucial part: I want any attributes forwarded to the proxy object here, without knowing beforehand what the names will be
    def __getattr__(self, attr):
        return getattr(self.proxy, attr)

# ======================================
# This code is the only I want to change to get things work

# Original __getattr__ function
original = DeviceProxy.__getattr__

# wrapper for the __getattr__ function to log/print out any attribute/parameter/argument/...
def mygetattr(device, key):
    attr = original(device, key) 
    if callable(attr):
        def wrapper(*args, **kw):
            print('%r called with %r and %r' % (attr, args, kw))
            return attr(*args, **kw)
        return wrapper
    else:  
        print "not callable: ", attr
        return attr

DeviceProxy.__getattr__ = mygetattr


# make an instance of the DeviceProxy class and call the double-dotted function
dev = DeviceProxy()
print dev.info(1)
print dev.obj.foo(3) 

我想要的是捕获对DeviceProxy的所有方法调用,以便能够打印所有参数/参数等等。在给定的示例中,当调用info(1)时,这非常有效,所有的信息都会被打印出来。 但是当我调用双点函数dev.obj.foo(3)时,我只得到一条消息,这是不可调用的。在

如何修改上面的代码,以便在第二种情况下也能得到我的信息?只能修改===下面的代码。在


Tags: theto代码selfobjreturnobjectfoo
1条回答
网友
1楼 · 发布于 2024-10-02 00:28:44

你只有一个__getattr__dev上,你想从这个__getattr__中,当你做dev.obj.foo时,可以访问{}。这是不可能的。属性访问不是作为一个整体访问的“点函数”。属性访问的顺序(点)从左到右,一次计算一个。在您访问dev.obj时,无法知道您以后将访问foo。方法dev.__getattr__只知道您正在访问dev上的哪些属性,而不知道您以后可以访问该结果的哪些属性。在

实现您想要的唯一方法是在obj中包含一些包装行为。你说你不能修改“基”/“派生”类,所以你不能这样做。理论上,您可以让DeviceProxy.__getattr__不返回被访问属性的实际值,而是将该对象包装在另一个代理中并返回代理。然而,这可能会有点棘手,并使您的代码更难理解和调试,因为您最终可能会有大量的对象被包装在瘦代理中。在

相关问题 更多 >

    热门问题