0

老实说,我不知道这样的东西是否存在,但我试图做一些研究,最终对一种叫做 d-Bus 的东西感到困惑,不确定这是否是这里要找的东西,

class BigClass(Object):
  def Foo(self):
     print 'calling foo'

  def Logger(self):
     print 'foo has been called'

a = BigClass()
a.foo()

我在这里尝试做的是在调用 foo() 时调用 Logger() 方法。我想创建某种事件/信号,当在我的类或所有方法中调用特定方法时,它将触发 logger()。

4

2 回答 2

1

I don't know your particular situation, but there is a good signal/callback lib called dispatch: http://pydispatcher.sourceforge.net/

But i prefer using Django dispatcher which was created based on PyDispatcher, but signal creation is more intuitive: https://github.com/django/django/blob/master/django/dispatch/dispatcher.py

what am trying to do here is invoke Logger() method when foo() is being called. I want to create some sort of a event/signal where it will fire up logger() when specific methods are called in my class or all methods.

Why don't you then call Logger method manually from foo method? Or better make a decorator to use it like:

class BigClass(Object):

  def Logger(self):
     print 'foo has been called'

  @log(Logger)
  def Foo(self):
     print 'calling foo'


a = BigClass()
a.foo()
于 2012-06-20T12:36:42.257 回答
0

虽然显式日志调用(或 warwaruk 建议的日志装饰器)是最直接的方法,但如果您愿意使用命名技巧,例如让逻辑foo方法由Foo. Python 是区分大小写的,所以它们是分开的和不同的。然后实现一个__getattr__方法,如下所示:

class AutoLogger(object):

    def __getattr__(self, attr):
        try:
            return self.__class__.__dict__[attr]
        except KeyError:
            func = self.__class__.__dict__[attr.capitalize()]
            return lambda *args, **kwargs: self.log_call(attr, func, *args, **kwargs)

    def log_call(self, func_name, func, *args, **kwargs):
        func(self, *args, **kwargs)
        print func_name, 'has been called (handled by', func_name.capitalize() + ')'

class BigAutoLoggerClass(AutoLogger):
    def Foo(self):
        print 'calling Foo'


b = BigAutoLoggerClass()
b.Foo()
print "---"
b.foo()

这产生:

calling Foo
---
calling Foo
foo has been called (handled by Foo)

bar将类似地由 实现Bar,依此类推。

如果您不喜欢这种随意的命名,也可以通过该sys.settrace()功能自动进行日志记录。但是,这会增加很多运行时开销,并且实际上仅适用于调试或低(ish)性能还可以的情况。

于 2012-06-20T13:24:43.947 回答