本文介绍了如何添加内置函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python编程的新手.如何使用C或C ++向python解释器添加新的内置函数和关键字?

I am new to python programming. How can I add new built-in functions and keywords to python interpreter using C or C++?

推荐答案

简而言之,可以在技术上将它们添加到Python的内建文件中(),但是几乎可以从来没有必要(通常​​被认为是一个非常糟糕的主意).

In short, it is technically possible to add things to Python's builtins, but it is almost never necessary (and generally considered a very bad idea).

从长远来看,很可能可以修改Python的源代码并添加新的内置函数,关键字等.但是,这样做的过程有点超出了问题的范围.

In longer, it's obviously possible to modify Python's source and add new builtins, keywords, etc… But the process for doing that is a bit out of the scope of the question as it stands.

如果您想了解有关如何修改Python源代码,如何编写可从Python调用的C函数等更多信息,请编辑问题以使其更具体.

If you'd like more detail on how to modify the Python source, how to write C functions which can be called from Python, or something else, please edit the question to make it more specific.

如果您是Python编程的新手,并且感觉到应该在日常工作中修改核心语言,那么这可能是您应该只是对其进行更多了解的一种指标. Python已未经修改地用于大量不同的问题域(例如, numpy 是扩展,便于科学计算,并且 Blender 将其用于3D动画),因此该语言很可能可以处理您的问题域也是.

If you are new to Python programming and you feel like you should be modifying the core language in your day-to-day work, that's probably an indicator you should simply be learning more about it. Python is used, unmodified, for a huge number of different problem domains (for example, numpy is an extension which facilitates scientific computing and Blender uses it for 3D animation), so it's likely that the language can handle your problem domain too.

†:您可以修改__builtin__模块以添加新的内置文件"……但这几乎肯定是一个坏主意:任何依赖于此的代码将非常困难(并且令人困惑)在原始应用程序上下文之外的任何地方使用.例如,考虑添加greater_than_zero内置",然后在其他地方使用它:

†: you can modify the __builtin__ module to "add new builtins"… But this is almost certainly a bad idea: any code which depends on it will be very difficult (and confusing) to use anywhere outside the context of its original application. Consider, for example, if you add a greater_than_zero "builtin", then use it somewhere else:

$ cat foo.py
import __builtin__
__builtin__.greater_than_zero = lambda x: x > 0

def foo(x):
    if greater_than_zero(x):
        return "greater"
    return "smaller"

任何试图阅读该代码的人都会感到困惑,因为他们不知道在何处定义greater_than_zero,而任何试图从未将greater_than_zero插入到__builtin__的应用程序中使用该代码的人都会赢了不能使用它.

Anyone who tries to read that code will be confused because they won't know where greater_than_zero is defined, and anyone who tries to use that code from an application which hasn't snuck greater_than_zero into __builtin__ won't be able to use it.

一种更好的方法是使用Python现有的import语句: http://docs. python.org/tutorial/modules.html

A better method is to use Python's existing import statement: http://docs.python.org/tutorial/modules.html

这篇关于如何添加内置函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 18:18