如何为python中的指针分配NULL值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22359737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to assign a NULL value to a pointer in python?
提问by sdream
I am C programmer. I am new to python. In C , when we define the structure of a binary tree node we assign NULL to it's right and left child as :
我是C程序员。我是python的新手。在 C 中,当我们定义二叉树节点的结构时,我们将 NULL 分配给它的左右孩子:
struct node
{
int val;
struct node *right ;
struct node *left ;
};
And when initializing a node , we write as :
当初始化一个节点时,我们写成:
val = some_value
right = NULL;
left = NULL;
Now my question is: how can we assign a NULL value to right and left pointers of the node in Python?
现在我的问题是:我们如何在 Python 中为节点的左右指针分配一个 NULL 值?
And how can we test against the Python version of NULL ? In C it would be:
我们如何针对 Python 版本的 NULL 进行测试?在 C 中,它将是:
if( ptr->right == NULL )
Thank you!
谢谢!
采纳答案by ApproachingDarknessFish
All objects in python are implemented via references so the distinction between objects and pointers to objects does not exist in source code.
python中的所有对象都是通过引用实现的,因此源代码中不存在对象和指向对象的指针之间的区别。
The python equivalent of NULLis called None(good info here). As all objects in python are implemented via references, you can re-write your struct to look like this:
相当于的 pythonNULL被称为None(这里有很好的信息)。由于python中的所有对象都是通过引用实现的,因此您可以将结构重写为如下所示:
class Node:
def __init__(self): #object initializer to set attributes (fields)
self.val = 0
self.right = None
self.left = None
And then it works pretty much like you would expect:
然后它的工作方式与您期望的非常相似:
node = Node()
node.val = some_val #always use . as everything is a reference and -> is not used
node.left = Node()
Note that unlike in NULLin C, Noneis not a "pointer to nowhere": it is actually the only instance of class NoneType.
Therefore, as Noneis a regular object, you can test for it just like any other object:
请注意,与NULLC中的不同,None它不是“指向无处的指针”:它实际上是class NoneType. 因此,与None常规对象一样,您可以像测试任何其他对象一样对其进行测试:
if node.left == None:
print("The left node is None/Null.")
Although since Noneis a singleton instance, it is considered more idiomatic to use isand compare for reference equality:
虽然因为None是单例实例,但使用is和比较引用相等性被认为更惯用:
if node.left is None:
print("The left node is None/Null.")
回答by limasxgoesto0
left = None
left is None #evaluates to True
回答by kenorb
Normally you can use None, but you can also use objc.NULL, e.g.
通常您可以使用None,但您也可以使用objc.NULL,例如
import objc
val = objc.NULL
Especially useful when working with C code in Python.
在 Python 中使用 C 代码时特别有用。
Also see: Python objc.NULL Examples
另请参阅:Python objc.NULL 示例

