Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.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_Dictionary_Methods - Fatal编程技术网

Python-使用内部方法修改字典中的对象

Python-使用内部方法修改字典中的对象,python,dictionary,methods,Python,Dictionary,Methods,我从Python开始,努力用类对象填充字典。 我的目标是用设备定义填充字典,并为所有设备创建接口。 问题是,当我试图用接口类对象填充内部列表时,设备字典中的所有对象在其列表中都有相同的接口定义,这肯定是不对的-接口定义必须是唯一的。 在此示例中,为2个设备生成结构。其中一个具有单个接口Gi1/1的定义,但输出显示两个设备在接口列表中具有相同的内容。 源代码如下: class PE: interfaces = [] def __init__(self, name):

我从Python开始,努力用类对象填充字典。 我的目标是用设备定义填充字典,并为所有设备创建接口。 问题是,当我试图用接口类对象填充内部列表时,
设备
字典中的所有对象在其列表中都有相同的接口定义,这肯定是不对的-接口定义必须是唯一的。 在此示例中,为2个设备生成结构。其中一个具有单个接口Gi1/1的定义,但输出显示两个设备在
接口
列表中具有相同的内容。 源代码如下:

class PE:
    interfaces = []
    def __init__(self, name):
        self.name = name
        print('creating device',self.name)

class Interface:
   def __init__(self, name):
        self.name = name

devices = {}
devices['bbr01'] = (PE('bbr01'))
devices['bbr02'] = (PE('bbr02'))
print('let\'s create an interface in  bbr01\'s list')
devices['bbr01'].interfaces.append(Interface('Gi1/1'))
print('what do we have in  bbr01\'s list?')
print(devices['bbr01'].interfaces[0].name)
print('what do we have in  bbr02\'s list?')
print(devices['bbr02'].interfaces[0].name)
输出:

    creating device bbr01
creating device bbr02
let's create an interface in  bbr01's list
what do we have in  bbr01's list?
Gi1/1
what do we have in  bbr02's list?
Gi1/1

接口成员是类级别的,而不是实例级别的

您需要将其更改为:

class PE(object):
    def __init__(self, name):
        self.name = name
        self.interfaces = []
        print('creating device',self.name)

接口成员是类级别的,而不是实例级别的

您需要将其更改为:

class PE(object):
    def __init__(self, name):
        self.name = name
        self.interfaces = []
        print('creating device',self.name)

题目听起来很简单,问题本身就相当冗长复杂。通过将实际问题及其性质与特定代码分离,您可以创建一个新的解决方案吗?清理了大多数数据字段-现在它非常紧凑,仍然显示了问题-问题标题听起来很简单,问题本身相当冗长和复杂。您是否可以通过将实际问题及其性质与特定代码分离来创建一个新的解决方案?清理了大多数数据字段-现在它非常紧凑,并且仍然显示了问题