在 Python 中为函数别名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14440552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Alias a function in Python
提问by Randomblue
I would like a copy of the printfunction that is called debug. How can I alias a function in Python?
我想要一份print名为的函数的副本debug。如何在 Python 中为函数设置别名?
采纳答案by Pavel Anossov
You can simply assign debug = printin Python 3.
您可以简单地debug = print在 Python 3 中赋值。
In Python 2 printisn't a function. There no way to give yourself a debugstatement that works exactly like print(print 1,, print 1 >> sys.stderretc.). Best you can do is write a wrapper around the printstatement:
在 Python 2print中不是函数。有没有办法给自己debug的作品完全一样的语句print(print 1,,print 1 >> sys.stderr等等)。你能做的最好的事情就是在print语句周围写一个包装器:
def debug(s):
print s
You can also disable the printstatement and use the Python 3 version:
您还可以禁用该print语句并使用 Python 3 版本:
from __future__ import print_function
debug = print
If you do this, you cannot use the statement version (print x) anymore. It's probably the way to go if you're not breaking any old code.
如果这样做,则不能再使用语句版本 ( print x)。如果您不破坏任何旧代码,这可能是要走的路。
回答by Steve Mayne
In Python 2.x you can do:
在 Python 2.x 中,您可以执行以下操作:
def debug(s):
print(s)
In 3.x you can just use assignment:
在 3.x 中你可以只使用赋值:
debug = print
回答by Andbdrew
You can just define a new function debuglike:
您可以定义一个新函数,debug例如:
def debug(text):
print text
回答by Weetu
It depends on your version of Python. Python 3 simply allows you to do this:
这取决于您的 Python 版本。Python 3 只允许你这样做:
debug = print
However, older versions consider printto be a built-in keyword, so you have to wrap it in your own function:
但是,旧版本认为print是内置关键字,因此您必须将其包装在您自己的函数中:
def debug(msg):
print(msg)
回答by jtpereyda
The defmethod has the advantage that tracebacks more clearly identify the alias. This could help a user who says, "What's 'print'?" if they only use debug(the alias):
该def方法的优点是回溯更清楚地识别别名。这可以帮助那些说“' print'是什么?”的用户。如果他们只使用debug(别名):
>>> def f():
... print x
>>> g = f
>>> g()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
NameError: global name 'x' is not defined
>>>
>>> def h():
... return f()
...
>>> h()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in h
File "<stdin>", line 2, in f
NameError: global name 'x' is not defined

