对象行为中的Python dicts?

2024-10-03 23:19:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用一个名称和它的邻居的dict,以及它引用这个邻居(不一定是邻居的名称)的标记来创建一个节点类

class node:
def __init__(self,name='',neighbors={}):
    self.name=name
    self.neighbors=neighbors

def addNeighbor(self,neighborTag,neighbor):
    if neighborTag not in self.neighbors.keys():
        self.neighbors[neighborTag] = neighbor

但是,当我执行以下操作时:

foo = node(name='foo')
foo.addNeighbor('fooneighbor',node(name='bar'))

dict条目{'foonneighbor',node object}也出现在foo.neighbors['foonneighbor'].neighbors中(我希望它是空的)

我猜这与dicts的工作方式有关,但我并不知道。有人能开导我吗


Tags: name标记self名称node节点foodef
1条回答
网友
1楼 · 发布于 2024-10-03 23:19:46

引用docs

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.:

def whats_on_the_telly(penguin=None):
    if penguin is None:
        penguin = []
    penguin.append("property of the zoo")
    return penguin

所以,你可以像这样解决你的问题

def __init__(self,name='',neighbors=None):
    self.name=name
    if neighbors == None:
       neighbors = dict() 
    self.neighbors=neighbors

相关问题 更多 >