【发布时间】:2018-02-11 23:39:59
【问题描述】:
我正在为我的班级使用 python2.7 编写 deepcopy 函数。我遇到了一个奇怪的问题 我的代码如下
import copy
from ctypes import *
class Graph (Structure):
_fields_ = [("numVertices", c_ulong),
("numEdges", c_ulong)]
def __init__(self):
self.numVertices = c_ulong(0)
self.numEdges = c_ulong(0)
def __deepcopy__(self,memo={}):
newInstance = Graph()
newInstance.numVertices = c_ulong(self.numVertices.value)
newInstance.numEdges = c_ulong(self.numEdges.value)
return newInstance
graph = Graph()
anotherGraph = copy.deepcopy(graph)
我收到以下错误:
<ipython-input-46-a0cdaa4ef3f7> in __deepcopy__(self, memo)
9 def __deepcopy__(self,memo={}):
10 newInstance = Graph()
---> 11 newInstance.numVertices = c_ulong(self.numVertices.value)
12 newInstance.numEdges = c_ulong(self.numEdges.value)
13 return newInstance
AttributeError: 'long' object has no attribute 'value'
如果你尝试:
type(graph.numVertices)
结果很长
我将 numVertices 声明为 c_ulong()。为什么会变长?
【问题讨论】:
-
我知道c_ulong的
value属性的类型是long。但我的问题是,为什么 c_ulong 类型的字段会变成 long 类型。您会看到 numVertices 是 c_ulong 类型,它应该有一个 value 属性。但是在__deepcopy__函数中,它的类型变成了 long 而不是 c_ulong 并且它根本没有 'value' 属性! -
我明白你的意思。我删除了我的错误答案。有趣的是,从课程中删除
_fields_后,您会得到预期的结果。