Skip to main content
 首页 » 编程设计

python之初始化列表在方法中显示为空

2025年05月04日11虾米哥

这是我的代码:

serial_list=[] 
dev_label = ["0","0"] 
context = Context() 
monitor = Monitor.from_netlink(context) 
monitor.filter_by(subsystem='block',device_type='partition') 
observer = GUDevMonitorObserver(monitor) 
 
print dev_label 
 
 
def device_connected(observer, device): 
    print dev_label 
 
    flag =False 
    for iden in serial_list : 
        if iden == device.__getitem__('ID_SERIAL_SHORT'): 
            flag=True 
 
    if flag ==False: 
 
        Welcome.device_count+=1 
        print Welcome.device_count 
        serial_list.append(device.__getitem__('ID_SERIAL_SHORT')) 
        dev_label[Welcome.device_count-1]=str(device.__getitem__('ID_FS_LABEL')) 
        label = gtk.Label('Device connected :: {0!r}'.format(dev_label[Welcome.device_count-1])) 
        Welcome.vbox.pack_start(label) 
        Welcome.window.show_all() 
 
    if Welcome.device_count<2: 
        label = gtk.Label('Connect the second device') 
        Welcome.vbox.pack_start(label) 
        Welcome.window.show_all() 
 
 
    else : 
        Exchange() 
 
observer.connect("device-added",device_connected) 
monitor.start() 
 
class Welcome: 
    device_count = 0     
    window = gtk.Window() 
    vbox= gtk.VBox(False, 5) 
 
 
    def __init__(self): 
 
        self.window.set_default_size(300, 300) 
        self.window.set_title("Welcome") 
 
        label = gtk.Label("Connect the desired device") 
 
        self.vbox.pack_start(label) 
        self.window.add(self.vbox) 
 
        self.window.connect("destroy", lambda q: gtk.main_quit()) 
        self.window.show_all() 

这是回溯:

['0', '0'] 
[] 
1 
Traceback (most recent call last): 
  File "project.py", line 36, in device_connected 
    dev_label[Welcome.device_count-1]=str(device.__getitem__('ID_FS_LABEL')) 
IndexError: list assignment index out of range 

如您所见,dev_label 列表在开始时被初始化为 ["0","0"]。但是,此列表在 device_connected 中显示为空。有人请告诉我出了什么问题!

请您参考如下方法:

Welcome.device_count 的值为 0,因此您分配的值为

array_name[0 - 1] = str(...); 

因此,Welcome.device_count 是导致错误的原因。

谢谢!