java是否与python __call__等效? [英] Does java have an equivalent to python __call__?

查看:224
本文介绍了java是否与python __call__等效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始学习python,我遇到了 __ call __ 方法。我理解当调用 __ init __ 时,通过运行一个简单的例子来调用 __ call __

Just started learning python, I've come across __call__ method. I understand when __init__ gets called and when __call__ gets called by running a simple example:

class Constructor:
    def __init__(self, a):
        print "__init__ called"

    def __call__(self):
        print "__call__ called"

    def dummy(self):
        print "a dummy method called"

print "creating x obj"
x = Constructor(1)
print "calling x object"
x()

控制台输出:

creating x obj
__init__ called
calling x object
__call__ called

我的问题是:


  1. 我来自java背景,我知道 __ init __ 映射到java构造函数,java是否等效于 __call __ 帮助我更好地理解这一点?

  2. 有人能给我一个简单的例子,说明何时 __ call __ can can有用吗?

  1. I come from java background, I know __init__ maps to java constructor, does java have an equivalent to __call__ to help me understand this better?
  2. Can someone give me a simple example of when __call__ can be useful?


推荐答案

__ call __ 等于重载() 一个类的运算符。这在C ++中是可能的,但不是Java。它允许一个人拥有功能对象(有时称为仿函数)。

__call__ equates to overloading the () operator on a class. This is possible in C++ but not Java. It allows one to have function objects (sometimes called functors).

在Python中,这些被称为可调用对象

In Python these are termed callable objects.

简单来说,这允许您将对象视为函数。

In simple terms, this allows you to treat an object as a function.

这些概念的实际用途超出了本答案的范围,但互联网上有大量信息。例如维基百科

The actual use for such concepts is beyond the scope of this answer but there is plenty of information around the internet. For example Wikipedia.

这篇关于java是否与python __call__等效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆