我主要是一个C++(因此是一个OO /命令式)程序员,我觉得很奇怪的是,在一个条件语句中,每个评估只能有一个语句,例如函数式语言Scheme中的if语句.
例如:
(let ((arg1 0) (arg2 1))
(if (> arg1 arg2)
arg1
arg2)))
Run Code Online (Sandbox Code Playgroud)
错误的例子:
(let ((arg1 0) (arg2 1))
(if (> arg1 arg2)
(arg1 (display "cool"))
(arg2 (display "not cool"))))
Run Code Online (Sandbox Code Playgroud)
给我一个错误的类型"程序应用程序:预期程序,给定:2;参数是:#void"
这可以通过将所述条件语句放入定义函数体内的不同语句中来解决,例如,条件语句的主体每次都有单独的语句,如下所示:
(if (condition) statement1a statement2a)
(if (condition) statement1b statement2b)
Run Code Online (Sandbox Code Playgroud)
等等...
不言而喻,这不太实际.更不用说重复的代码开销了.
我在这里遗漏了什么,还是没有别的办法?
工会是否有控制结构来测试当前正在使用哪个成员(或者它是否有任何成员)?我问这个是因为未定义的行为在你的程序中永远不是一件好事.
基本上我想要一个带有参数列表的装饰器,它不仅包含一个能够从@ - 和常规形式调用的函数.我已经"设计"了一个快速的解决方法,但它很难看并立即在@ -form中执行一个函数,这是一个不受欢迎的副作用(这当然是由于返回body_two()).
def status_display_with_comment(comment, closure = None):
def body_one(function = None):
def body_two():
print(comment)
#an ugly workaround to be able to run both the @- and regular forms
if function != None:
print("Entering", function.__name__)
function()
print("Exited", function.__name__)
elif closure != None:
print("Entering", closure.__name__)
closure()
print("Exited", closure.__name__)
return body_two()
return body_one
def a_function():
print('a_function executes')
@status_display_with_comment(comment = 'some comment')
def a_function_with_comment():
print('a_function_with_comment executes')
a_function_status_display_with_comment = status_display_with_comment(closure = a_function, comment = 'a comment')
a_function_status_display_with_comment()
Run Code Online (Sandbox Code Playgroud)
提前致谢.
PS:我必须围绕整个封闭的事情.这很有趣,因为它可以像Scheme一样递送(很久以前对我来说).
在Python中,有没有办法将不同的装饰器分配给函数作为变量?
例如(以下代码显然不执行):
def status_display(function):
def body():
print("Entering", function.__name__)
function()
print("Exited", function.__name__)
return body
def call_counter(function):
counter = 0
def body():
function()
nonlocal counter
counter += 1
print(function.__name__, 'had been executed', counter, 'times')
return body
def a_function():
print('a_function executes')
# problems start here
# is there a working alternative to this false syntax?
@status_display
a_function_with_status_display = a_function()
@call_counter
a_function_with_call_counter = a_function()
# for an even crazier feat
# I knew this wouldn't work even before executing it
a_function_with_status_display = @status_display a_function() …
Run Code Online (Sandbox Code Playgroud)