python中实例变量和属性之间的区别?
因此,编写扩展的 python 文档是这样说的:
“我们想要公开我们的实例 变量作为属性。有一个 有很多方法可以做到这一点。这 最简单的方法是定义成员 定义:
静态 PyMemberDef Noddy_members[] = { {“第一个”,T_OBJECT_EX,offsetof(诺迪,第一个),0, “名”}, {“最后”,T_OBJECT_EX,offsetof(诺迪,最后),0, “姓”}, {“数字”,T_INT,offsetof(诺迪,数字),0, “诺迪号码”}, {NULL} /* 哨兵 */ };
并将定义放入 tp_members 插槽:
Noddy_members, /* tp_members */"
但是,我们已经将实例变量放入了 Noddy 结构中:
typedef struct {
PyObject_HEAD
PyObject *first;
PyObject *last;
int number;
} Noddy;
所以我的问题是为什么我们将它们放在两个地方。我的印象是,这是因为我们希望类型和实例都拥有它们,以便在实例更新后保留类型值。但如果是这样的话,如果我们更改类属性,实例值如何更新?像这样:
>>> class foo(object): x = 4
...
>>> f = foo()
>>> f.x
4
>>> foo.x = 5
>>> f.x
5
So, the python docs for writing extension says this:
"We want to expose our instance
variables as attributes. There are a
number of ways to do that. The
simplest way is to define member
definitions:static PyMemberDef Noddy_members[] = { {"first", T_OBJECT_EX, offsetof(Noddy, first), 0, "first name"}, {"last", T_OBJECT_EX, offsetof(Noddy, last), 0, "last name"}, {"number", T_INT, offsetof(Noddy, number), 0, "noddy number"}, {NULL} /* Sentinel */ };
and put the definitions in the
tp_members slot:Noddy_members, /* tp_members */"
However, we have already put the instance variables in the Noddy struct:
typedef struct {
PyObject_HEAD
PyObject *first;
PyObject *last;
int number;
} Noddy;
so my question is that why we put them in both places. My impression is that, that is because we want both type and the instance to have them so that we preserve the types values once the instance get updated. But If thats the case, how does the instance value get updated if we change the class attribute? like this:
>>> class foo(object): x = 4
...
>>> f = foo()
>>> f.x
4
>>> foo.x = 5
>>> f.x
5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编写 C 扩展是一个复杂的过程,因为您必须编写 C 代码,并且必须向 Python 提供足够的信息,以便它可以像操作 Python 数据一样操作您的 C 数据。您必须两次提及该结构体的成员:一次是为了让 C 编译器知道如何创建该结构体,然后是为了让 Python 知道数据在哪里以及它的名称。
C 没有自省能力,因此您无法(例如)在运行时获取结构体成员的列表。 PyMemberDef 数组提供了该信息。
Writing a C extension is a complex process, because you have to write C code, and you have to provide enough information to Python so that it can manipulate your C data as if it were Python data. You have to mention the members of the struct twice: once for the C compiler to know how to make the struct, and then again so that Python knows where the data is, and what it is called.
C has no introspection ability, so you can't (for example), get a list of members of a struct at runtime. The array of PyMemberDef provides that information.
好吧,我做了研究,是的,实例变量和属性是不同的,那是因为类实例和类有单独的字典。正如文档中所述::
所以基本上 Noddy 结构保存实例变量。 Noddy_members 保存属性。此外:
还:
Ok So I did my research and yes instance variables and attributes are different and thats because classes instances and classes have separate dictionaries. As said in the documentation::
So basically the Noddy struct holds the instance variables. The Noddy_members holds the attributes. Furthermore:
Also: