hasattr、getattr、setattr

在Python中,hasattr()getattr()setattr()是一组内置函数,用于对对象的属性进行操作和查询。这些函数提供了一种方便的方式来检查对象是否具有特定属性,获取属性的值,以及设置属性的值。

1. hasattr

hasattr()函数是一种重要的工具,用于判断对象是否具有指定的属性或方法

1.1 语法

hasattr(object, name)
  • object – 对象。
  • name – 字符串,属性名或方法名。
  • 如果对象有该属性返回 True,否则返回 False。

1.2 案例

  • 案例1
   gs = max(int(self.model.stride.max() if hasattr(self.model, "stride") else 32), 32)  # grid size (max stride)
  • 案例2
if not hasattr(model, "names"):
   model.names = default_class_names()
  • 案例3
data = model.args["data"] if hasattr(model, "args") and isinstance(model.args, dict) else ""
if prompts and hasattr(self.predictor, "set_prompts"):  # for SAM-type models
     self.predictor.set_prompts(prompts)
  • 案例4
@property
 def names(self):
      """Returns class names of the loaded model."""
      return self.model.names if hasattr(self.model, "names") else None
  • 案例5
  def _close_dataloader_mosaic(self):
       """Update dataloaders to stop using mosaic augmentation."""
       if hasattr(self.train_loader.dataset, "mosaic"):
           self.train_loader.dataset.mosaic = False
       if hasattr(self.train_loader.dataset, "close_mosaic"):
           LOGGER.info("Closing dataloader mosaic")
           self.train_loader.dataset.close_mosaic(hyp=self.args)

  • 案例6
  names = model.module.names if hasattr(model, "module") else model.names
  • 案例7
 if not self.is_fused():
           for m in self.model.modules():
               if isinstance(m, (Conv, Conv2, DWConv)) and hasattr(m, "bn"):
                   if isinstance(m, Conv2):
                       m.fuse_convs()
                   m.conv = fuse_conv_and_bn(m.conv, m.bn)  # update conv
                   delattr(m, "bn")  # remove batchnorm
                   m.forward = m.forward_fuse  # update forward
               if isinstance(m, ConvTranspose) and hasattr(m, "bn"):
                   m.conv_transpose = fuse_deconv_and_bn(m.conv_transpose, m.bn)
                   delattr(m, "bn")  # remove batchnorm
                   m.forward = m.forward_fuse  # update forward
               if isinstance(m, RepConv):
                   m.fuse_convs()
                   m.forward = m.forward_fuse  # update forward
           self.info(verbose=verbose)
  • 案例7
name, m = list((model.model if hasattr(model, "model") else model).named_children())[-1]
  • 案例8
if not hasattr(model, "stride"):
       model.stride = torch.tensor([32.0])
  • 案例9
 model = model.fuse().eval() if fuse and hasattr(model, "fuse") else model.eval()  # model in eval mode
 if hasattr(self, "nm"):
           self.__delattr__("nm")
       if hasattr(self, "bn"):
           self.__delattr__("bn")
       if hasattr(self, "id_tensor"):
           self.__delattr__("id_tensor")

2. getattr

获取object对象的属性的值,如果存在则返回属性值,如果不存在分为两种情况,一种是没有default参数时,会直接报错;给定了default参数,若对象本身没有name属性,则会返回给定的default值;如果给定的属性name是对象的方法,则返回的是函数对象。需要调用函数对象来获得函数的返回值;调用的话就是函数对象后面加括号,如func之于func()

2.1 语法

getattr(object, name[, default])
  • object – 对象。
  • name – 字符串,对象属性或方法。
  • default – 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。

2.2 案例

  • 案例1
 file = Path(
            getattr(model, "pt_path", None) or getattr(model, "yaml_file", None) or model.yaml.get("yaml_file", "")
        )
  • 案例2
  nc = getattr(model, "nc", 10)  # number of classes
  • 案例3
    本例中,给定的name是一个方法,通过getattr返回一个函数对象,调用的话就是函数对象后面加括号,然后传入相关的函数参数。
 if name in ("Adam", "Adamax", "AdamW", "NAdam", "RAdam"):
            optimizer = getattr(optim, name, optim.Adam)(g[2], lr=lr, betas=(momentum, 0.999), weight_decay=0.0)
        elif name == "RMSProp":
            optimizer = optim.RMSprop(g[2], lr=lr, momentum=momentum)
        elif name == "SGD":
            optimizer = optim.SGD(g[2], lr=lr, momentum=momentum, nesterov=True)
        else:
            raise NotImplementedError(
                f"Optimizer '{name}' not found in list of available optimizers "
                f"[Adam, AdamW, NAdam, RAdam, RMSProp, SGD, auto]."
                "To request support for addition optimizers please visit https://github.com/ultralytics/ultralytics."
            )

  • 案例4
  if getattr(dataset, "rect", False) and shuffle:
            LOGGER.warning("WARNING ?? 'rect=True' is incompatible with DataLoader shuffle, setting shuffle=False")
            shuffle = False

3. setattr

setattr() 函数的功能相对比较复杂,它最基础的功能是修改类实例对象中的属性值。其次,它还可以实现为实例对象动态添加属性或者方法, 设置属性值时,该属性不一定是存在。

3.1 语法

setattr(object, name, value)

3.2 案例

  • 案例1
r = self.new()
for k in self._keys:
   v = getattr(self, k)
   if v is not None:
       setattr(r, k, getattr(v, fn)(*args, **kwargs))
  • 案例2
for k in "imgsz", "batch":  # allow arg updates to reduce memory on resume if crashed due to CUDA OOM
    if k in overrides:
        setattr(self.args, k, overrides[k])

  • 案例3
def reshape_outputs(model, nc):
        """Update a TorchVision classification model to class count 'n' if required."""
        name, m = list((model.model if hasattr(model, "model") else model).named_children())[-1]  # last module
        if isinstance(m, Classify):  # YOLO Classify() head
            if m.linear.out_features != nc:
                m.linear = nn.Linear(m.linear.in_features, nc)
        elif isinstance(m, nn.Linear):  # ResNet, EfficientNet
            if m.out_features != nc:
                setattr(model, name, nn.Linear(m.in_features, nc))
  • 案例4
    通过setattr,实现将b的所有属性和方法,copy给a
def copy_attr(a, b, include=(), exclude=()):
    """Copies attributes from object 'b' to object 'a', with options to include/exclude certain attributes."""
    for k, v in b.__dict__.items():
        if (len(include) and k not in include) or k.startswith("_") or k in exclude:
            continue
        else:
            setattr(a, k, v)

代码参考:https://github.com/ultralytics/ultralytics