argparse.ArgumentParser()应用,hasattr(), getattr(), setatt() 作用,raise应用,super(父类).__init__()应用

本文详细解析了Python中argparse模块用于处理命令行参数的方法,包括定位参数和可选参数的设定。同时,深入探讨了hasattr(), getattr(), setattr()函数在对象属性管理中的应用,以及super()在继承中的作用。最后,介绍了如何通过raise NotImplementedError确保子类实现特定方法。
部署运行你感兴趣的模型镜像

1、argparse.ArgumentParser().add_argument 的作用:

import argparse
parser = argparse.ArgumentParser()

parser.add_argument('input_dir', type=str, help='Directory with unaligned images.')
parser.add_argument('output_dir', type=str, help='Directory with aligned face thumbnails.')
parser.add_argument('--image_size', type=int,
                        help='Image size (height, width) in pixels.', default=182)
parser.add_argument('--margin', type=int,help='Margin for the crop around the bounding 
                        box (height, width) in pixels.', default=44)
parser.add_argument('--random_order', help='Shuffles the order of images to 
                        enable alignment using multiple processes.', action='store_true')
parser.add_argument('--gpu_memory_fraction', type=float,help='Upper bound on the 
                    amount of GPU memory that will be used by the process.', default=1.0)

parser.parse_args(['hah','aha'])

结果:

add_argument()是用来指定程序需要接受的命令参数

input_dir这一类直接用单引号括起来的表示定位参数

margin这一类前加有  为可选参数,并规定定位参数必选,可选参数可选。

 

2、hasattr(), getattr(), setatt() 作用

  • hasattr(object, name)

判断object对象中是否存在name属性,当然对于python的对象而言,属性包含变量和方法

有则返回True,没有则返回False;

需要注意的是name参数是string类型,所以不管是要判断变量还是方法,其名称都以字符串形式传参;getattr和setattr也同样;

 

  • getattr(object, name[, default]):

获取object对象的属性的值,如果存在则返回属性值

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

注意,如果给定的方法func()是实例函数,则不能写getattr(A, 'func')(),因为fun()是实例函数的话,是不能用A类对象来调用的,应该写成getattr(A(), 'func')();

实例函数和类函数的区别可以简单的理解一下,

实例函数定义时,直接def func(self):,这样定义的函数只能是将类实例化后,用类的实例化对象来调用

类函数定义时,需要用@classmethod来装饰,函数默认的参数一般是cls,类函数可以通过类对象来直接调用,而不需要对类进行实例化;

 

  • setattr(object, name, value):

给object对象的name属性赋值value

如果对象原本存在给定的属性name,则setattr会更改属性的值为给定的value;

如果对象原本不存在属性name,setattr会在对象中创建属性,并赋值为给定的value;

一般先判断对象中是否存在某属性

如果存在则返回;如果不存在,则给对象增加属性并赋值;

参看博客链接:https://www.cnblogs.com/zanjiahaoge666/p/7475225.html

 

3、raise NotImplementedError('initialization method [%s] is not implemented') 

      要求继承的子类,在调用父类方法时一定要实现其方法

Python编程中raise可以实现报出错误的功能,而报错的条件可以由程序员自己去定制。在面向对象编程中,可以先预留一个方法接口不实现,在其子类中实现。

如果要求其子类一定要实现,不实现的时候会导致问题,那么采用raise的方式就很好。

而此时产生的问题分类是NotImplementedError。

从程序的执行结果可以看出,只要相应的方法接口进行了实现,在执行的时候未实施的错误便不会报出

参考:https://www.jb51.net/article/138623.htm

 

 

4、super(Student,self).__init__()

继承自父类的属性进行初始化而且是用父类的初始化方法来初始化继承的属性

也就是说,子类继承了父类的所有属性和方法,父类属性自然会用父类方法来进行初始化。

当然,如果初始化的逻辑与父类的不同,不使用父类的方法,自己重新初始化也是可以的。

 

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

修改,未解析的引用 'core',应为语句,实际为 Py:RBRACE,,应为语句,实际为 Py:RPAR,,应为语句,实际为 Py:DEDENT,,,应为语句,实际为 Py:EXCEPT_KEYWORD,,应为语句结束,,应为语句,实际为 Py:AS_KEYWORD,,应为表达式,,应为 'except' 或 'finally',找不到模块 'get_ui_config',,语句似乎不起任何作用,,局部变量 'e' 可能在赋值前引用,,代码#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 应用上下文模块 (最终优化版) """ import os import logging import threading from typing import Dict, Any # 延迟导入以避免循环依赖 # from .event_center import EventCenter class AppContext: """ 应用上下文单例类 集中管理所有全局组件和配置 """ _instance = None _lock = threading.Lock() def __new__(cls): """单例模式实现""" with cls._lock: if cls._instance is None: cls._instance = super().__new__(cls) cls._instance._initialized = False return cls._instance def __init__(self): """初始化方法 (确保只执行一次)""" if getattr(self, '_initialized', False): return # 初始化日志 self._logger = logging.getLogger(__name__) self._logger.setLevel(logging.INFO) # 初始化核心组件 self._initialized = True self._event_center = None self.dialog_manager = None self.main_ui = None self.number_pool = None self.modules: Dict[str, Any] = {} # 初始化配置 self.config: Dict[str, Any] = { 'debug': False, 'version': '1.0' } # 计算项目根目录 self.project_root = os.path.abspath( os.path.join(os.path.dirname(__file__), '..') ) self._logger.info(f"AppContext 初始化完成 | 项目根目录: {self.project_root}") try: from core.ui_config import get_ui_config ui_config = get_ui_config() self.config.update({ "theme": ui_config.get("theme"), "language": ui_config.get("language"), }) # 可以添加更多需要的字段 }) except ImportError as e: self._logger.error(f"无法导入核心模块: {e}") raise @property def event_center(self): """事件中心访问器""" if self._event_center is None: # 延迟导入以避免循环依赖 from .event_center import EventCenter self._event_center = EventCenter() self._logger.warning("创建了新的事件中心实例") return self._event_center @event_center.setter def event_center(self, value): """设置事件中心实例 - 使用鸭子类型检查""" if not hasattr(value, 'publish') or not callable(value.publish): raise TypeError("事件中心必须实现publish方法") self._event_center = value # 全局单例实例 app_context = AppContext() __all__ = ['AppContext', 'app_context']
最新发布
09-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值