【发布时间】:2011-12-29 22:18:09
【问题描述】:
我有一些 python 模块,它有一个 ModuleClass 类,我无法修改该类。
现在,我希望能够代理方法调用并添加某些日志记录功能。我认为这应该通过转发对象和相应的代理 (following Effective Java, Item 16) 来完成。
我想出的python 伪代码如下。
(抱歉,我的 python 真的很糟糕,如果您能在此处指出错误,我将不胜感激。
# This is what I've got in my module and this code cannot be changed.
class ModuleClass(object):
def method1(self):
# Some implementation
pass()
def method2(self):
# Some implementation
pass()
# Simple forwarding proxy to avoid the situation described in Effective Java, I16
# However, in Java this class would usually be extending the interface, not
# inheriting 'ModuleClass' (I'm confused and don't know how to do the same
# in python).
class ForwardingModuleClass(ModuleClass):
# 'proxifiedObject' is
def __init__(self, proxifiedObject):
self.proxifiedObject = proxifiedObject
# Overriding the first method
def method1(self):
return self.proxifiedObject.method1()
# Same for method2...
class LoggingModuleClass(ForwardingModuleClass):
# 'classThatActuallyDoesStuff' should be an instance of 'ModuleClass'.
def __init__(self, classThatActuallyDoesStuff):
# Sorry for my bad knowledge of python syntax, but
# I assume I can initialize the superclass here using
# the supplied 'ModuleClass' instance.
super(classThatActuallyDoesStuff)
# Overriding the first method.
def method1(self):
print("Yay! This 'method1' really logs something!")
return super.method1()
# Overriding the second method.
def method2(self):
print("Yay!!!! This 'method2' also does something cool!")
return super.method2()
现在,我想,如果写得正确,这将起作用,并且我将拥有我最初的 ModuleClass 的日志记录代理。
如果有错误或者不是pythonish,请指出。
另外,我怀疑这可以使用decorators 轻松完成, 但不幸的是,我想不出合适的方法,我不知道如果ModuleClass 已经有了会发生什么一些方法装饰器。
你也可以帮我吗?
【问题讨论】:
-
在编写 Python 时忘记 Java。两者的语义甚至并不接近。
-
@CatPlusPlus 好的,但我想
python应该有一个很好的方法来解决这个问题。 -
Python 错误:super 不是对象而是方法。要调用父母构造函数,您必须调用 super().__init__() 并调用 parent 方法,您应该调用 super().method() (我想您使用的是 python 3...)
标签: python logging decorator proxy-classes