定义没有括号的函数? [英] Defining function without the brackets?

查看:146
本文介绍了定义没有括号的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我的问题听起来很愚蠢,而且在语言定义中可能会明确禁止这个概念,但由于我不知道这个禁令,所以我想知道是否有人能够对此作出说明。总之,我想定义一个python函数,我可以从python shell调用,但是我想避免使用括号。有些情况下函数不需要参数,然后方括号似乎只表示我们正在处理函数。这样的例子是,如果想打印当前工作目录。我可以定义一个函数为:

pre $ def $ p $ def
print os.getcwd

然后我可以从shell调用它作为



<$ p $

如果我想要一个函数我可以称之为

  pwd 

这完全有可能吗?

解决方案

如果不修改语言或者shell。



如果你想使用Python作为shell,你应该试试 IPython ,它允许您定义可以使用的宏,而无需键入多个键。它也可以让你做!pwd ,你可以将它分配给一个变量以及 x =!pwd 。它甚至可以通过编写 fx 而不是 f(x)

$ b来调用单个参数函数。
$ b

BTW Haskell是一种使用空格列出参数的语言,即:Python中的 f(1,2,3)应该是 f 1 2 3 在Haskell中,在shell中,只需输入 action 即可执行任何IO操作。



我忘了你也可以做一个破解:

  class Pwd(object ):
def __repr __(self):
#做pwd命令
#以字符串形式返回结果
pwd = Pwd()

现在,当您在shell中键入pwd时,它会调用 __ repr __ 来获取字符串表示形式物体。不幸的是,由于Python语言强制执行此操作,因此您仅限于返回一个字符串(而不是表示当前目录中表示文件/文件夹的字符串列表,如果您正在执行ls)。

b

I understand that my question might sound stupid, and that there might be something in the language definition that explicitly prohibits this notion, but since I don't know about this prohibition, I was wondering whether someone could shed some light on it. In short, I would like to define a python function that I could call from the python shell, but I would like to avoid the brackets. There are cases when a function does not require an argument, and then the bracket only seems to indicate that we are dealing with a function. Such an example would be, if one wants to print the current working directory. I can define a function as

def pwd():
    print os.getcwd()

and then I can call it from the shell as

pwd()

But what if I would like to have a function that I can call as

pwd

Is this possible at all?

解决方案

You can't do this without modifying the language or the shell.

If you want to use Python as a shell, you should really try IPython, it allows you to define macros that you can use without typing as many keys. It also lets you do !pwd, you can assign this to a variable as well x = !pwd. It even lets you call single argument functions by writing f x instead of f(x).

BTW Haskell is a language that uses spaces for list of arguments, i.e: f(1,2,3) in Python would be f 1 2 3 in Haskell, and in the shell any IO action can be executed by just typing action.

I forgot there's also a hack you can do:

class Pwd(object):
    def __repr__(self):
        # do pwd command
        # return result in string form
pwd = Pwd()

Now when you type pwd in the shell, it will call __repr__ to get a string representation of the object. Unfortunately, you're restricted to returning a string (as opposed to say, a list of strings representing the files/folders in the current directory, if you were implementing ls) because the python language forces this.

这篇关于定义没有括号的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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