【发布时间】:2021-03-23 14:50:56
【问题描述】:
我遇到了这个我认为可能与内存有关的错误。
我有一个类 Page()
class Page:
index = [None] * 3
is_word = False #If this is false, then is not an end word, just a passing index
页面用于构建动态结构,索引是指向其他页面的指针(或地址)数组。 最初这个地址是空的,只有在添加时它们才会包含另一个页面的地址。
如您所见,当创建任何页面时,索引的所有值都为 none。
在我的代码的一部分中,我有这个:
self.index[1] = Page() #Create new page
new_page = self.index[1]
执行此代码后,初始页面应包含在数组索引中:
- 无
- 新创建的页面
- 无
并且 new_page 应该包含在数组索引中:
- 无
- 无
- 无
问题在于 new_page 包含
- 无
- 新创建的页面
- 无
这没有任何意义,我没有将新页面的地址分配给任何行中索引的这个位置。
调试我现在可以看到
self.index[1] = Page() #Create new page 被执行,这个新创建的页面已经在索引中包含了错误的值。
我不习惯 python(我是一名 Java 和 C 程序员),在我第一个 python 项目的某个时候,我假设 python 处理内存,我不必太在意它。
我认为错误的发生是因为原始数组是空的,并且我正在为其分配一个 Page 对象,所以我可能会导致内存问题。 这将在 C 中使用 reallocs 处理,但我不知道如何在 python 中解决这个问题,或者如果 python 中不需要这种内存分配并且问题是我没有看到的另一个问题。
P.D. 根据要求,完整代码:
class Page:
index = [None] * 256 #One for each ascii character
is_word = False #If this is false, then is not an end word, just a passing index
def insert_word(self, word):
if(len(word) == 1): #Final condition
ascii_number_word = ord(word[0])
page_of_index = self.index[ascii_number_word]
if(page_of_index == None): #If the index is not present
page_of_index = self.index[ascii_number_word] = Page()
page_of_index.is_word = True #Mark page as word
else:
letter = word[0]
resulting_word = word[1:]
ascii_number_letter = ord(letter)
page_of_index = self.index[ascii_number_letter]
if(page_of_index == None): #index does not exist, then create
self.index[ascii_number_letter] = Page() #Create new page
page_of_index = self.index[ascii_number_letter]
page_of_index.insert_word(resulting_word)
【问题讨论】:
-
能否请您添加您正在运行的类的完整代码?如果我们能看到它,也许我们就能发现错误。
-
你试过我下面的解决方案了吗?如果它有效,如果它让你满意,请接受答案,因为它会给我带来声誉:)
-
完成,接受,非常感谢
标签: python pointers data-structures dynamic memory-address