我想使用Jython,你可以用Python做任何你可以用Java做的事情。
相反,Python有PyPy编译器,这很酷 - 具有多个支持的虚拟机(Java Runtime,LLVM,.net和Python IIRC),多个垃圾回收器,多个实现(Stackless)等。我知道Java有很多虚拟机选择,但PyPy的增长是惊人的,因为它是用RPython编写的 - 一种相当高效的语言。
另外,Java是否可以在1个文件和少于20行的情况下做到这一点,而无需导入库?显然,这两种语言都有可以做到这一点的库,但我只是在谈论语言的灵活性。
class Logger(object): # boilerplate code
def log(self,level,msg,*args,**kwargs): # *args, **kwargs = flexible arguments
self._log(level,msg,*args,**kwargs) # call with flexible argments
def _log(self,level,msg,*args,**kwargs):
# override me at runtime :)
# I think Java people call this Dependency Runtime Injection
if level>1:
print msg,args,kwargs
logger = Logger() # boilerplate code
def logged(level): # what pattern do you call this?
def logged_decorator(function): # and this?
def func(*args,**kwars):
name = func.__name__ # look ma, reflective metaprogramming!
logger.log(level,name,*args,**kwargs)
return func(*args,**kwargs)
return func # boilerplate code
return logged_decorator # boilerplate code
使用示例:
@logged
def my_func(arg1,arg2):
# your code here
pass