Skip to main content
 首页 » 编程设计

python之这段 python 代码中发生了什么

2024年11月01日9kerrycode

以下片段来自 pyusb tutuorial .它用于查找所有连接的打印机:

import usb.core 
import usb.util 
import sys 
 
class find_class(object): 
    def __init__(self, class_): 
        self._class = class_ 
    def __call__(self, device): 
        # first, let's check the device 
        if device.bDeviceClass == self._class: 
            return True 
        # ok, transverse all devices to find an 
        # interface that matches our class 
        for cfg in device: 
            # find_descriptor: what's it? 
            intf = usb.util.find_descriptor( 
                                    cfg, 
                                    bInterfaceClass=self._class 
                                ) 
            if intf is not None: 
                return True 
 
        return False 
 
printers = usb.core.find(find_all=1, custom_match=find_all(7)) 

这个类似乎有多个返回 bool 值的点。发送了多少返回?

我也无法理解这段代码如何搜索连接到系统的所有打印机。 这段代码中让我无法理解的是:

  • device 是列表/元组吗?如果是,此代码如何通过执行一次 if device.bDeviceClass == self._class: 检查所有设备?

  • 这一行发生了什么:self._class = class_

  • 为什么类 find_class 从未在 printers = usb.core.find(find_all=1, custom_match=find_all(7)) 中实例化

    如果您使用过 pyusb/任何 USB 程序,请告诉我如何操作。

请您参考如下方法:

Is device a list/tuple?

device 是一个 usb.core.Device .遍历它yields configurations .

If yes, how does this code check all the devices by executing if device.bDeviceClass == self._class: just once?

事实并非如此。您错过了“因此,要真正找到连接到系统的所有打印机,我们需要遍历所有配置,然后遍历所有接口(interface)并检查其中一个接口(interface)的 bInterfaceClass 字段是否等于 7”的部分。

what is happening in this line: self._class = class_

正如其所言。它将该参数中的对象绑定(bind)到该属性。供以后使用。

why is the class find_class never instantiated in printers = usb.core.find(find_all=1, custom_match=find_all(7))

因为有人有想法。最后一部分应该是 ...=find_class(7)。