太原建站网站模板,wordpress 线报主题,Wordpress编辑工具,做线上网站的风险分析在Python中#xff0c;hasattr()、getattr()和setattr()是一组内置函数#xff0c;用于对对象的属性进行操作和查询。这些函数提供了一种方便的方式来检查对象是否具有特定属性#xff0c;获取属性的值#xff0c;以及设置属性的值。
1. hasattr
hasattr()函数是一种重要…在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 modelsself.predictor.set_prompts(prompts)案例4
propertydef 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 Falseif hasattr(self.train_loader.dataset, close_mosaic):LOGGER.info(Closing dataloader mosaic)self.train_loader.dataset.close_mosaic(hypself.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 convdelattr(m, bn) # remove batchnormm.forward m.forward_fuse # update forwardif isinstance(m, ConvTranspose) and hasattr(m, bn):m.conv_transpose fuse_deconv_and_bn(m.conv_transpose, m.bn)delattr(m, bn) # remove batchnormm.forward m.forward_fuse # update forwardif isinstance(m, RepConv):m.fuse_convs()m.forward m.forward_fuse # update forwardself.info(verboseverbose)案例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 modeif 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], lrlr, betas(momentum, 0.999), weight_decay0.0)elif name RMSProp:optimizer optim.RMSprop(g[2], lrlr, momentummomentum)elif name SGD:optimizer optim.SGD(g[2], lrlr, momentummomentum, nesterovTrue)else:raise NotImplementedError(fOptimizer {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 ⚠️ rectTrue is incompatible with DataLoader shuffle, setting shuffleFalse)shuffle False3. 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 OOMif 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 moduleif isinstance(m, Classify): # YOLO Classify() headif m.linear.out_features ! nc:m.linear nn.Linear(m.linear.in_features, nc)elif isinstance(m, nn.Linear): # ResNet, EfficientNetif 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:continueelse:setattr(a, k, v)代码参考https://github.com/ultralytics/ultralytics