Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
保存Python中自定义类实例的状态更改_Python_Python 3.x_Tree - Fatal编程技术网

保存Python中自定义类实例的状态更改

保存Python中自定义类实例的状态更改,python,python-3.x,tree,Python,Python 3.x,Tree,我很难弄清楚为什么我的打印(节点(3).value)正在打印0。有什么想法吗 当我运行这个代码时,我得到 First: 6 Value: 8 Children: [9] First: 8 Value: 23 Children: [9] First: 3 Value: 3 Children: [5] First: 6 Value: 8 Children: [7] First: 4 Value: 20 Children: [8] First: 1 Value: 17 Children: [8] Fi

我很难弄清楚为什么我的
打印(节点(3).value)
正在打印
0
。有什么想法吗

当我运行这个代码时,我得到

First: 6 Value: 8 Children: [9]
First: 8 Value: 23 Children: [9]
First: 3 Value: 3 Children: [5]
First: 6 Value: 8 Children: [7]
First: 4 Value: 20 Children: [8]
First: 1 Value: 17 Children: [8]
First: 8 Value: 23 Children: [10]
First: 5 Value: 11 Children: [8]
First: 1 Value: 17 Children: [2]
0
有什么想法吗?我知道我不会把节点保存在任何地方,但我的大脑无法控制它。 任何帮助都将不胜感激,谢谢

# Complete the primeQuery function below.
n = 10
first = [6, 8, 3, 6, 4, 1, 8, 5, 1]
second = [9, 9, 5, 7, 8, 8, 10, 8, 2]
values = [17, 29, 3, 20, 11, 8, 3, 23, 5, 15]
queries = [1, 8, 9, 6, 4, 3]


class Node(object):
    def __init__(self, data, value=0):
        self.data = data
        self.value = value
        self.children = []

    def addChild(self, child):
        self.children.append(child)

    def setValue(self, givenV):
        self.value = givenV


def primeQuery(n, first, second, values, queries):
    i = 0
    while i < n - 1:
        f = Node(first[i], values[first[i] - 1])

        s = Node(second[i], values[second[i] - 1])

        f.addChild(s.data)

        print(f"First: {f.data} Value: {f.value} Children: {f.children}")

        i += 1

    print(Node(3).value)


primeQuery(n, first, second, values, queries)
#完成下面的primeQuery功能。
n=10
第一个=[6,8,3,6,4,1,8,5,1]
秒=[9,9,5,7,8,8,10,8,2]
值=[17,29,3,20,11,8,3,23,5,15]
查询=[1,8,9,6,4,3]
类节点(对象):
定义初始化(self,data,value=0):
self.data=数据
自我价值=价值
self.children=[]
def addChild(self,child):
self.children.append(子级)
def设定值(自身、给定NV):
self.value=givenV
def primeQuery(n,第一,第二,值,查询):
i=0
而i
语句

Node(3).value
创建
节点
对象,将
数据
设置为
3
设置为
0
(默认参数),因此当您获取其
时,它将返回
0

如果要创建
节点
对象,然后重新使用它们,应该将它们存储在某种容器中

假设

  • 数据
    字段是节点
    的可散列唯一标识符
  • 如果已创建
    节点
    ,并且我们正在传递不同的
    ——旧的
    仍然存在
我在这里看到了至少两种方法:

  • 在顶层创建容器,在创建时显式地向其添加
    节点
    s,然后使用它访问它们

    def primeQuery(n, first, second, values, queries):
        i = 0
        # top-level container of ``Node``s
        nodes = {}
    
        def get_or_create_node(data, value):
            try:
                # trying to access already created ``Node``
                result = nodes[data]
            except KeyError:
                # no ``Node`` found, create it...
                result = Node(data, value)
                # ... and register
                nodes[data] = result
            return result
    
        while i < n - 1:
            f = get_or_create_node(first[i], values[first[i] - 1])
            s = get_or_create_node(second[i], values[second[i] - 1])
    
            f.addChild(s.data)
    
            print(f"First: {f.data} Value: {f.value} Children: {f.children}")
    
            i += 1
    
        print(nodes[3].value)
        # we can return ``nodes`` here if we want to use them outside of given function
    
  • 对先前方法的扩展:使用缓存已创建节点的全局函数限制节点的创建:

    # in module namespace
    def get_or_create_node(data, value=0,
                           *,
                           # hack, see **note**
                           cache={}):
        # we've moved class definition inside of a function to restrict its instances creation
        class Node(object):
            def __init__(self, data, value):
                self.data = data
                self.value = value
                self.children = []
    
            def addChild(self, child):
                self.children.append(child)
    
            def setValue(self, givenV):
                self.value = givenV
    
        try:
            result = cache[data]
        except KeyError:
            result = Node(data, value)
            cache[data] = result
        return result
    
    注意:这里我们使用的是带有可变默认参数的“hack”,更多信息可以在中找到)

    然后,当我们需要创建/访问
    节点
    对象时,我们应该在任何地方使用这个函数

    def primeQuery(n, first, second, values, queries):
        i = 0
        while i < n - 1:
            f = get_or_create_node(first[i], values[first[i] - 1])
            s = get_or_create_node(second[i], values[second[i] - 1])
    
            f.addChild(s.data)
    
            print(f"First: {f.data} Value: {f.value} Children: {f.children}")
    
            i += 1
    
        print(get_or_create_node(3).value)
    
  • 在第二种方法中:将
    value
    参数的默认值设置为
    None
    ,并检查它是否被指定为

    def get_or_create_node(data, value=None,
                           *,
                           cache={}):
        class Node(object):
            def __init__(self, data, value):
                self.data = data
                self.value = value
                self.children = []
    
            def addChild(self, child):
                self.children.append(child)
    
            def setValue(self, givenV):
                self.value = givenV
    
        try:
            result = cache[data]
        except KeyError:
            if value is None:
                # default value
                value = 0
            result = Node(data, value)
            cache[data] = result
        else:
            if value is not None:
                result.setValue(value)
        return result
    
对象继承
如果我们使用的是Python3——则无需将
对象指定为基类,它将默认设置(请参见),因此

class Node(object):
    ...
i = 0
while i < n - 1:
    ...
    i += 1
我们可以简单地写

class Node:
    ...
当我们有
for
-loop和
range
对象时,我们不需要使用
-loop&手动递增
i
,因此

class Node(object):
    ...
i = 0
while i < n - 1:
    ...
    i += 1
我还认为这是一个输入错误,因为我们跳过了
I
等于
n-1
的大小写,所以我们可以修复它:

for i in range(n):
    ...
最后,我们可以看到,当我们可以对
first
&
second
列表
s元素进行使用和迭代时,就不需要使用
i
索引

for first_data, second_data in zip(first, second):
    f = get_or_create_node(first_data, values[first_data - 1])
    s = get_or_create_node(second_data, values[second_data - 1])

    f.addChild(s.data)

    print(f"First: {f.data} Value: {f.value} Children: {f.children}")

你没有保存你的
节点
对象
f
s
节点(3)
将创建一个
节点
,其
值为0
@AzatIbrakov,噢,糟了!嗯,但我对如何真正拯救他们有点困惑?@KlausD,是的,看到我的代码是有道理的。但是,是否有一个关于如何保存对象的示例片段?这取决于您试图构建的数据结构
for first_data, second_data in zip(first, second):
    f = get_or_create_node(first_data, values[first_data - 1])
    s = get_or_create_node(second_data, values[second_data - 1])

    f.addChild(s.data)

    print(f"First: {f.data} Value: {f.value} Children: {f.children}")