简体   繁体   English

为什么Python将引用计数保持为False和True?

[英]Why does Python keep a reference count on False and True?

I was looking at the source code to the hasattr built-in function and noticed a couple of lines that piqued my interest: 我正在查看hasattr内置函数的源代码,并注意到一些引起我兴趣的行:

Py_INCREF(Py_False);
return Py_False;

...

Py_INCREF(Py_True);
return Py_True;

Aren't Py_False and Py_True global values? 不是Py_FalsePy_True全局值吗? Just out of sheer curiosity, why is Python keeping a reference count for these variables? 出于纯粹的好奇心,为什么Python保留这些变量的引用计数?

It's to make all object handling uniform. 这是为了使所有对象处理均匀。 If I'm writing C code that handles a return value from a function, I have to increment and decrement the reference count on that object. 如果我正在编写处理函数返回值的C代码,我必须递增和递减该对象的引用计数。 If the function returns me True, I don't want to have to check to see if it's one of those special objects to know whether to manipulate its reference count. 如果函数返回True,我不想检查它是否是那些特殊对象之一,知道是否操纵它的引用计数。 I can treat all objects identically. 我可以完全相同地对待所有对象。

By treating True and False (and None, btw) the same as all other objects, the C code is much simpler throughout. 通过将True和False(和None,btw)视为与所有其他对象相同,C代码在整个过程中要简单得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM