我今天在编码并发现了一些东西.如果我打开一个新的解释器会话(IDLE)并检查使用该dir函数定义的内容,我会得到:
$ python
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', …Run Code Online (Sandbox Code Playgroud) 我正在寻找使用 Python3 C API 来添加内置函数。我这样做只是为了帮助我熟悉 Python C API 的练习。这个问题的答案很好地解释了为什么人们可能不想这样做。无论如何,我想foo向Pythonbuiltins模块添加一个函数。
这是我到目前为止所做的( foo.c):
#include <Python.h>
#include <stdio.h>
static PyObject*
foo(PyObject *self, PyObject *args){
printf("foo called");
return Py_None;
}
char builtin_name[] = "builtins";
char foo_name[] = "foo";
char foo_doc[] = "foo function";
static PyMethodDef foo_method = {foo_name, foo, METH_NOARGS, foo_doc};
PyMODINIT_FUNC
PyInit_foo(void){
PyObject *builtin_module = PyImport_ImportModule(builtin_name);
PyModule_AddFunctions(builtin_module, &foo_method);
return builtin_module;
}
Run Code Online (Sandbox Code Playgroud)
我将其放置在Modules/Python 源目录中的目录中。
给出一个简单的类
class Vector(object):
def __init__(self, value):
self.value = value
def __abs__(self):
return math.sqrt(sum([x**2 for x in self.value]))
def __round__(self, *n):
return [round(x,*n) for x in self.value]
Run Code Online (Sandbox Code Playgroud)
为什么在抱怨而不是期望的情况下abs(Vector([-3,4]))正确屈服,这又如何解决?5round(Vector([-3.1,4]))TypeError: a float is required[-3,4]
我知道round通常应该返回一个浮点数,但对于这个例子中的向量,可能的意义可能没有歧义,为什么这不能简单地被覆盖?我真的必须继承numbers.Real或定义Vector(...).round(n)吗?