问题描述
我遇到了我认为可能与内存有关的错误。
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 中不需要这种内存分配,而问题是我没有看到的另一个问题。
PD 根据要求,完整代码:
class Page:
index = [None] * 256 #One for each ascii character
is_word = False #If this is false,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 中被认为是静态的。试试这个:
class Page:
def __init__(self):
self.index = [None] * 3
self.is_word = False
def create_middle_page(self):
self.index[1] = Page()
new_page = self.index[1]
print(new_page)
def __str__(self):
return str(self.index)
page = Page()
page.create_middle_page()
print(page)
输出:
[None,None,None]
[None,<__main__.Page object at 0x7f3bc6326fd0>,None]
在此处查看第 9.3.5 节:https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables
来自上述文档:
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self,name):
self.name = name # instance variable unique to each instance