Обнаружил странную проблему при написании b+деревьев с использованием Python.Python

Программы на Python
Гость
Обнаружил странную проблему при написании b+деревьев с использованием Python.

Сообщение Гость »


Tree node structure:

Код: Выделить всё

class BPlusNode:
def __init__(self,isleaf = True,val=[],parent=None,children=[]):
self.values = val
self.children = children
self.parent = parent
self.isleaf = isleaf
self.order=3
where the bug appears:

Код: Выделить всё

def split(self,node):
if (len(node.children)==0 and len(node.values) 5):
sys.exit()
print('',new_root.values)

node.parent=new_root
self.root=new_root
parent=new_root
input 3,1,4,5 in order
the output is:
the output
strangely the new node has already been assigned values
but the program runs correctly if I write like this:

Код: Выделить всё

new_root=BPlusNode(isleaf=False,val=[],parent=None,children=[])
Why does this happens?
I noticed a mechanism of default parameter in python:
operations on mutable objects with default parameters will be preserved
for example:

Код: Выделить всё

cnt=2
def f(data=[]):
global cnt
data.append(1)
print(data)
data[0]=cnt
cnt+=1
return data
f()
f()
f()
the output will be:

Код: Выделить всё

[1]
[2, 1]
[3, 1, 1]
but in my code:

Код: Выделить всё

def __init__(self,isleaf = True,val=[],parent=None,children=[]):
the parameter "val" has not been operated
Is this problem related to this mechanism?
Or it is caused by other reasons?


Источник: https://stackoverflow.com/questions/781 ... ing-python

Вернуться в «Python»