Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the built-in functions of Python and how to use them

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "what are the built-in functions of Python and how to use them". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. please follow the editor's train of thought to study and learn "what are the built-in functions of Python and how to use them".

1.abs

The function of abs is to take the absolute value of an integer or the module of a complex number.

Static PyObject * builtin_abs (PyObject * module, PyObject * x) {return PyNumber_Absolute (x);}

This function calls PyNumber_Absolute.

/ / Objects/abstract.cPyObject * PyNumber_Absolute (PyObject * o) {PyNumberMethods * m; if (o = = NULL) {return null_error ();} / / get operation cluster PyNumberMethods m = o-> ob_type- > tp_as_number; / / call nb_absolute if (m & m-> nb_absolute) return m-> nb_absolute (o) Return type_error ("bad operand type for abs ():'% .200s'", o);}

Let's take an integer as an example, whose nb_absoulte points to long_absolute.

/ / Objects/longobject.cstatic PyObject * long_abs (PyLongObject * v) {if (Py_SIZE (v))

< 0) //如果 v 小于 0,那么取相反数 return long_neg(v); else //否则返回本身 return long_long((PyObject *)v);} 由于 Python3 的整数是以数组的方式存储的,所以不会直接取相反数,还要做一些额外的处理,但从数学上直接理解为取相反数即可。 2.all 接收一个可迭代对象,如果里面的元素全部为真,则返回 True;只要有一个不为真,则返回 False。 static PyObject *builtin_all(PyObject *module, PyObject *iterable){ PyObject *it, *item; PyObject *(*iternext)(PyObject *); int cmp; //获取可迭代对象的迭代器 it = PyObject_GetIter(iterable); if (it == NULL) return NULL; //拿到内部的 __next__ 方法 iternext = *Py_TYPE(it)->

Tp_iternext; for (;;) {/ / iterative element item = iternext (it); / / returns NULL, indicating the exception / / one is the StopIteration / / thrown at the end of the iteration, and the other is the exception if (item = = NULL) break that occurs during the iteration / / determine whether the Boolean value of item is true / / cmp > 0 is true / / cmp = = 0 is false / / cmp

< 0 表示解释器调用出错(极少发生) cmp = PyObject_IsTrue(item); Py_DECREF(item); if (cmp < 0) { Py_DECREF(it); return NULL; } //只要有一个元素为假,就返回 False if (cmp == 0) { Py_DECREF(it); Py_RETURN_FALSE; } } Py_DECREF(it); //PyErr_Occurred() 为真表示出现异常了 if (PyErr_Occurred()) { //判断异常是不是 StopIteration if (PyErr_ExceptionMatches(PyExc_StopIteration)) //如果是,那么表示迭代正常结束 //PyErr_Clear() 负责将异常清空 PyErr_Clear(); else return NULL; } //走到这,说明所有的元素全部为真 //返回 True,等价于 return Py_True Py_RETURN_TRUE;} 因此 all 就是一层 for 循环,但它是 C 的循环,所以比我们写的 Python 代码快。 3.any 接收一个可迭代对象,只要里面有一个元素为真,则返回 True;如果全为假,则返回 False。 static PyObject *builtin_any(PyObject *module, PyObject *iterable){ //源码和 builtin_all 是类似的 PyObject *it, *item; PyObject *(*iternext)(PyObject *); int cmp; //获取可迭代对象的迭代器 it = PyObject_GetIter(iterable); if (it == NULL) return NULL; //拿到内部的 __next__ 方法 iternext = *Py_TYPE(it)->

Tp_iternext; for (;;) {/ / iterative elements item = iternext (it); if (item = = NULL) break; cmp = PyObject_IsTrue (item); Py_DECREF (item); if (cmp)

< 0) { Py_DECREF(it); return NULL; } //只要有一个为真,则返回 True if (cmp >

0) {Py_DECREF (it); Py_RETURN_TRUE;}} Py_DECREF (it); if (PyErr_Occurred ()) {if (PyErr_ExceptionMatches (PyExc_StopIteration)) PyErr_Clear (); if else return NULL;} / / is all false, False Py_RETURN_FALSE;} 4.callable is returned

Determines whether an object is callable.

Static PyObject * builtin_callable (PyObject * module, PyObject * obj) {return PyBool_FromLong ((long) PyCallable_Check (obj));} PyBool_FromLong converts an integer to a Boolean value, so it depends on whether PyCallable_Check returns 0 or non-0. IntPyCallable_Check (PyObject * x) {if (x = = NULL) return 0; return x-> ob_type- > tp_call! = NULL;}

The logic is very simple. Whether an object is callable or not depends on whether its type object implements _ _ call__.

5.dir

If no object is received, the current local space is returned; otherwise, the names of all properties of an object are returned.

Static PyObject * builtin_dir (PyObject * self, PyObject * args) {PyObject * arg = NULL; / / either do not receive a parameter or receive a parameter / / if no parameter is received, then arg is NULL, otherwise it is the parameter if (! PyArg_UnpackTuple (args, "dir", 0,1, & arg) return NULL; return PyObject_Dir (arg);}

This function calls PyObject_Dir.

/ / Objects/object.cPyObject * PyObject_Dir (PyObject * obj) {/ / when obj is NULL, we do not pass parameters, then return the local space / / otherwise return the names of all attributes of the object return (obj = = NULL)? _ dir_locals (): _ dir_object (obj);}

Let's take a look at the _ dir_locals function first.

/ / Objects/object.cstatic PyObject * _ dir_locals (void) {PyObject * names; PyObject * locals; / / get the current local space locals = PyEval_GetLocals (); if (locals = = NULL) return NULL; / / get all key. Note: PyMapping_Keys returns the list names = PyMapping_Keys (locals); if (! names) return NULL If (! PyList_Check (names)) {PyErr_Format (PyExc_TypeError, "dir (): expected keys () of locals to be a list,"not'% .200s'", Py_TYPE (names)-> tp_name); Py_DECREF (names); return NULL;} / / sort if (PyList_Sort (names)) {Py_DECREF (names) Return NULL;} / / return return names;}

It's relatively simple, and then there's _ dir_object, which has a lot of code, so I won't look at it here. But the logic is simple: call the object's dir method, sort the resulting list and return it.

6.id

Looking at the memory address of the object, we know that although everything in Python is an object, all we get is a pointer to the object. For example, id (name) is to look at the address where the variable name points to the object, which is, to put it bluntly, name itself. So you can just turn the pointer into an integer and return it.

Static PyObject * builtin_id (PyModuleDef * self, PyObject * v) {/ / convert v to an integer and return PyObject * id = PyLong_FromVoidPtr (v); if (id & & PySys_Audit ("builtins.id", "O", id)

< 0) { Py_DECREF(id); return NULL; } return id;}7.locals 和 globals 这两者是查看当前的 local 空间和 global 空间,显然直接通过栈帧的 f_locals 和 f_globals 字段即可获取。 static PyObject *builtin_locals_impl(PyObject *module){ PyObject *d; //在内部会通过线程状态对象拿到栈帧 //再通过栈帧的 f_locals 字段拿到 local 空间 d = PyEval_GetLocals(); Py_XINCREF(d); return d;}static PyObject *builtin_globals_impl(PyObject *module){ PyObject *d; //和 PyEval_GetLocals 类似 d = PyEval_GetGlobals(); Py_XINCREF(d); return d;}8.hash 获取对象的哈希值。 static PyObject *builtin_hash(PyObject *module, PyObject *obj){ Py_hash_t x; //在内部会调用 obj ->

Ob_type-> tp_hash (obj) x = PyObject_Hash (obj); if (x =-1) return NULL; return PyLong_FromSsize_t (x);} 9.sum

Receive an iterable object and calculate their sum. But there is one thing to pay attention to.

Print (sum ([1,2,3]) # 6try: print (sum (["1", "2", "3"])) except TypeError as e: print (e) # unsupported operand type (s) for +: 'int' and' str'

Why, strings obviously support addition, why not? In fact, sum can also accept the second parameter, which is 0 if we don't pass it.

In other words, sum ([1,2,3]) is actually 0 + 1 + 2 + 3; similarly, sum (["a", "b", "c") is actually 0 + "a" + "b" + "c"; so the above error message does not support the addition of instances of type int and str.

Try: print (sum (["1", "2", "3"], "") except TypeError as e: print (e) # sum () can't sum strings [use''.join (seq) instead] # We still got it wrong It can only be explained in theory # but Python suggests that we use join# as an example: print (sum ([[1], [2], [3])) except TypeError as e: print (e) # unsupported operand type (s) for +: 'int' and' list'# tells us that int instances and list instances cannot be added # replace the second parameter with an empty list print (sum ([1]) [2], [3]], []) # [1, 2, 3] # what if it's not an empty list? Print (sum ([[1], [2], [3]], ["Gu Ming Di Jue"]) # ['Gu Ming Di Jue', 1, 2, 3]

So sum adds the elements in the second parameter and the first parameter (iterable object) in turn, and then takes a look at the underlying implementation.

Static PyObject * builtin_sum_impl (PyObject * module, PyObject * iterable, PyObject * start) {/ / result is the return value, which is initially equal to the second parameter / / if the iterable object is empty, then the second parameter / / such as sum ([], 123) is returned, which is 123 PyObject * result = start; PyObject * temp, * item, * iter. / / get the type object of the iterable object iter = PyObject_GetIter (iterable); if (iter = = NULL) return NULL; / / if result is NULL, we did not pass the second parameter if (result = = NULL) {/ / then the result assignment is 0 result = PyLong_FromLong (0); if (result = = NULL) {Py_DECREF (iter) Return NULL;}} else {/ / otherwise, check whether it is of str, bytes, bytearray type / / if so, still report an error and prompt to use the join method if (PyUnicode_Check (result)) {PyErr_SetString (PyExc_TypeError, "sum () can't sum strings [use''.join (seq) instead]") Py_DECREF (iter); return NULL;} if (PyBytes_Check (result)) {PyErr_SetString (PyExc_TypeError, "sum () can't sum bytes [use b''.join (seq) instead]"); Py_DECREF (iter); return NULL } if (PyByteArray_Check (result)) {PyErr_SetString (PyExc_TypeError, "sum () can't sum bytearray [use b''.join (seq) instead]"); Py_DECREF (iter); return NULL;} Py_INCREF (result) } # ifndef SLOW_SUM / / here is a fast branch / / suppose all elements are integers if (PyLong_CheckExact (result)) {/ / iterate all integers, add / /...} if (PyFloat_CheckExact (result)) {/ / iterate all floating point numbers Add / /...} # endif / / if not all integers or floating point numbers, execute the generic logic for ( ;) {/ / iterative element item = PyIter_Next (iter); if (item = = NULL) {/ * error, or end-of-sequence * / if (PyErr_Occurred ()) {Py_DECREF (result); result = NULL;} break } / / and result add temp = PyNumber_Add (result, item); Py_DECREF (result); Py_DECREF (item); result = temp; if (result = = NULL) break;} Py_DECREF (iter); / / return return result;}

A small sum, the code is really a lot of it, we also omitted part of it.

10.getattr 、 setattr 、 delattr

These should be familiar, so let's take a look at getattr, which gets a property of the object and can also specify a default value.

Static PyObject * builtin_getattr (PyObject * self, PyObject * const * args, Py_ssize_t nargs) {PyObject * v, * name, * result; / / the number of parameters must be 2 or 3 / object, attribute name, optional default value if (! _ PyArg_CheckPositional ("getattr", nargs, 2, 3) return NULL; / / get object and attribute name v = args [0]; name = args [1] / / name must be the string if (! PyUnicode_Check (name)) {PyErr_SetString (PyExc_TypeError, "getattr (): attribute name must be string"); return NULL } / / the _ _ getattr__, of the calling object cannot find the default value if (nargs > 2) {if (_ PyObject_LookupAttr (v, name, & result) = = 0) {PyObject * dflt = args [2]; Py_INCREF (dflt); return dflt;}} else {result = PyObject_GetAttr (v, name) } return result;}

Similarly, setattr is the _ _ setattr__,delattr of the calling object is the _ _ delattr__ of the calling object.

Thank you for reading, the above is the content of "Python built-in functions have and how to use", after the study of this article, I believe you have a deeper understanding of what Python built-in functions have and how to use this problem, the specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report