如何使用匿名对象函数和重写方法将Java转换为Python

2024-10-03 17:23:42 发布

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

还有其他与此类似的stackoverflowquestions,但不是针对我需要重写函数的问题。在

我想将以下Java代码转换为Python:

import Someclass;

Someclass obj = new Someclass("stringarg") {
    @Override
    void do(x) {
      // Do extra stuff on function
      super.do(x);
    }
}

我需要为此显式地创建一个伪类吗?这是否可以在一个像Java代码这样的语句中转换成Python?在

使用:Python2.7.6、Java1.8

这将在Jython中完成,其中Someclass是一个导入的Java库。在

任何帮助都将不胜感激。谢谢。在

乳房:

  • 对于那些和我有相同问题但import类是一个抽象类的人:

多亏了DNA的link,我只不过在他的方法中添加了一个超级语句,如下所示:

^{pr2}$
  • 对于那些导入类不是抽象类的人,DNA和algrebe的代码已经可以工作了,但也只是添加了缺少的super:

    ...
    super(Someclass, self).do(x)
    

Tags: 函数代码importobjnew抽象类语句java
2条回答

如果我理解正确的话,你有一个带有方法的类,你需要重写一个函数,而不必继承这个类并重写它。 Monkey Patching是解决这个问题的一种方法。在

根据Jython Concurrency

Your code may be different, but Python gives you good tools to avoid action at a distance. You can use closures, decorators, even sometimes selectively monkey patching modules. Take advantage of the fact that Python is a dynamic language, with strong support for metaprogramming, and remember that the Jython implementation makes these techniques accessible when working with even recalcitrant Java code.

class SomeClass(object):
    def __init__(self):
        self.a = "a"

    def foo(self):
        print "Base Foo"

    def bar(self):
        print "Base bar"
# new foo should execute something and then call the existing one
# i take it this is why you needed "super"
oldfoo = SomeClass.foo
def newFoo(self, name="default name"):
    print "Overridden %s" % name
    oldfoo(self)

# completely replace bar
def newBar(self):
    print "Overridden bar"

SomeClass.foo = newFoo
SomeClass.bar = newBar

obj = SomeClass()
obj.foo()
obj.bar()

如果您想重写/修补特定对象的方法(而不是在类级别,如algrebe的回答中所述),您可以这样做,但您需要注意方法是否正确绑定,如this article中所述

下面是一个可运行的示例:

import types

class Someclass():

  def __init__(self, x):
    self.x = x

  def do(self):
    print self.x

if __name__ == "__main__":

  def patch(self):
    print "goodbye"

  obj = Someclass("hello")
  obj.do  = types.MethodType(patch, obj)

  obj.do()    # prints "goodbye"

相关问题 更多 >