Python-VBA函数之旅-getattr函数

ops/2024/9/22 23:38:43/

目录

一、getattr函数的常见应用场景:    

二、getattr函数使用注意事项:

1、getattr函数:

1-1、Python:

1-2、VBA:

2、推荐阅读:

个人主页:https://blog.csdn.net/ygb_1024?spm=1010.2135.3001.5421



一、getattr函数的常见应用场景:    

        getattr函数在 Python 中有许多实际应用场景,尤其是在处理对象属性、动态访问属性、实现灵活的 API 和框架等方面。常见的应用场景有:

1、动态属性管理:当你不确定一个对象是否有某个属性,或者属性名在运行时才能确定时,可以使用getattr()函数。例如,在处理配置文件或用户输入时,你可能需要根据这些动态信息来访问对象的属性。

2、实现可选参数或默认值:在某些情况下,你可能想为对象的属性提供默认值,以防该属性不存在。getattr()函数的 “default” 参数非常适合这种情况。

3、实现灵活的API:在构建API或库时,你可能希望允许用户通过字符串来访问函数或方法,而不是直接调用它们。这可以通过将函数或方法作为对象的属性,并使用getattr()函数来实现。

4、插件和扩展系统:在构建可扩展的系统时,getattr()函数可以用于动态加载和执行插件或扩展。例如,一个框架可能允许用户通过添加具有特定方法的对象来扩展其功能。

5、配置文件和设置管理:在处理配置文件或应用程序设置时,getattr()函数可以用来动态地获取配置选项的值。这允许你在不修改代码的情况下更改配置,并使代码更加模块化和可维护。

6、与外部库或模块交互:当与外部库或模块交互时,你可能不知道它们的确切属性或方法名称,或者这些名称可能在不同的版本中有所变化。使用getattr()函数可以使你的代码更加灵活和健壮,因为它允许你动态地访问这些属性或方法。

7、动态类创建:结合type()函数,你可以使用getattr()函数动态地创建类。

8、结合装饰器使用:你可以使用装饰器和getattr()函数结合来动态地添加或修改对象的属性或方法。

        总之,由于 Python 的动态性,getattr()函数的应用非常广泛,几乎可以在任何需要动态访问或操作对象属性的地方使用。

二、getattr函数使用注意事项:

        在使用 Python 中的getattr()函数时,需注意以下事项:

1、异常处理:如果尝试获取的对象没有指定的属性,并且没有提供 `default` 参数,`getattr()` 会引发 `AttributeError`。因此,你应该始终准备好处理这种异常,或者使用 `default` 参数来避免它。

2、属性名称作为字符串:getattr()函数的第二个参数必须是字符串,表示要获取的属性的名称。如果你传递了非字符串类型的参数,会引发 `TypeError`。

3、区分方法和属性:如果你使用getattr()函数获取的是一个方法而不是一个属性,你需要记得调用这个方法(加上括号),否则,你会得到一个方法对象而不是它的返回值。

4、安全性和权限:在使用getattr()函数访问对象的属性时,要注意不要违反封装原则或访问不应该被外部访问的属性。如果对象的设计意图是隐藏某些属性或方法,你应该尊重这一点,并仅通过对象提供的公共接口进行交互。

5、避免过度使用:虽然getattr()函数提供了很大的灵活性,但过度使用它可能会使代码难以理解和维护。在大多数情况下,直接访问对象的属性或调用方法更加清晰和直接。只有在确实需要动态访问属性或实现某种特定逻辑时,才应使用getattr()函数。

6、与对象特殊方法的区别:getattr()函数是一个内置函数,用于从对象中获取属性。而 `__getattr__` 和 `__getattribute__` 是对象的特殊方法,用于在属性访问失败时定义自定义行为。它们通常在类定义中使用,而不是在普通的代码逻辑中。在使用这些特殊方法时要特别小心,因为它们会改变对象属性访问的基本行为。

1、getattr函数:
1-1、Python:
python"># 1.函数:getattr
# 2.功能:用于获取对象的属性值
# 3.语法:getattr(object, name [,default])
# 4.参数:
# 4-1、object:必须,对象。Python内置了一些基本的对象类型,包括但不限于:
#   4-1-1、 数字(Numbers):# int:整数# float:浮点数# complex:复数
#   4-1-2、 序列(Sequences):# list:列表,可以包含任意类型的元素# tuple:元组,与列表类似但不可变# str:字符串,字符序列# bytes:字节序列# bytearray:可变字节序列# memoryview:内存视图,是原始数据的不同解释
#   4-1-3、集合(Sets):# set:无序且不包含重复元素的集合# frozenset:不可变的集合
#   4-1-4、映射(Mappings):# dict:字典,键值对映射
#   4-1-5、布尔值(Booleans):# bool:布尔类型,只有两个值:True和False
#   4-1-6、类型(Types):# type:类型对象,用于描述其他对象的数据类型
#   4-1-7、其他内置类型:# NoneType:只有一个值None,表示空或没有值# ellipsis:...,通常用于切片操作或表示省略# slice:表示切片对象,用于切片操作# range:表示不可变的整数序列,通常用于循环# property:用于获取、设置或删除属性的内置装饰器类型# function:函数对象# method:方法对象,即绑定到类实例的函数# classmethod和staticmethod:特殊的方法类型,分别表示类方法和静态方法# module:模块对象# traceback、frame和code:与异常和调试相关的对象
# 4-2. name:必须,字符串,对象属性
# 4-3、default:可选,默认返回值,若不提供该参数,在没有对应属性时,将触发AttributeError错误
# 5.返回值:返回对象属性
# 6.说明:
# 7.示例:
# 应用1:动态属性管理
# 访问对象属性
class MyClass:def __init__(self):self.my_attribute = "Hello, Python!"
obj = MyClass()
# 使用getattr访问属性
attribute_value = getattr(obj, 'my_attribute')
print(attribute_value)
# Hello, Python!# 灵活处理属性不存在的情况
class MyClass:def __init__(self):self.existing_attribute = "I exist!"
obj = MyClass()
# 尝试访问一个不存在的属性,使用default参数来避免AttributeError
attribute_value = getattr(obj, 'non_existing_attribute', 'Default value')
print(attribute_value)
# Default value# 动态调用方法
class MyClass:def say_hello(self):print("Hello!")def say_goodbye(self):print("Goodbye!")
obj = MyClass()
# 根据用户输入动态调用方法
method_name = input("Enter method name (say_hello or say_goodbye): ")
if hasattr(obj, method_name):getattr(obj, method_name)()
else:print(f"No such method: {method_name}")
# Enter method name (say_hello or say_goodbye): say_hello
# Hello!# 处理嵌套对象
class InnerClass:def __init__(self):self.value = "Inner value"
class OuterClass:def __init__(self):self.inner = InnerClass()
obj = OuterClass()
# 使用getattr访问嵌套对象的属性
inner_value = getattr(getattr(obj, 'inner'), 'value')
print(inner_value)
# Inner value# 动态设置属性
class MyClass:pass
obj = MyClass()
# 使用setattr动态设置属性
setattr(obj, 'new_attribute', 'This is a new attribute')
# 使用getattr获取刚刚设置的属性
attribute_value = getattr(obj, 'new_attribute')
print(attribute_value)
# This is a new attribute# 实现链式调用
class Chainable:def __init__(self):self.value = 0def add(self, value):self.value += valuereturn selfdef result(self):return self.value
obj = Chainable()
result = getattr(getattr(obj, 'add')(5), 'add')(10).result()
print(result)
# 15# 应用2:实现可选参数或默认值
class User:def __init__(self, name):self.name = nameself.age = None
user = User("Myelsa")
age = getattr(User, "age", 18)  # 如果age不存在,则返回18
print(age)
# 18# 应用3:实现灵活的API
class API:def method1(self):return "Method 1 called"def method2(self):return "Method 2 called"
api = API()
method_name = input("请输入要调用的方法名(method1 或 method2):")
result = getattr(api, method_name, lambda: "Invalid method")()
print(result)
# 请输入要调用的方法名(method1 或 method2):method1
# Method 1 called# 应用4:插件和扩展系统
import os
class PluginBase:def execute(self):raise NotImplementedError("Subclasses must implement this!")
plugins = []
def load_plugins(directory):for filename in os.listdir(directory):if filename.endswith(".py"):module_name = os.path.splitext(filename)[0]module = importlib.import_module(f"plugins.{module_name}")for attr_name in dir(module):attr = getattr(module, attr_name)if isinstance(attr, type) and issubclass(attr, PluginBase):plugins.append(attr())
def run_plugins():for plugin in plugins:plugin.execute()
# 加载并执行插件
load_plugins("plugins_myelsa") # 假设存在插件plugins_myelsa
run_plugins()# 应用5:配置文件和设置管理
class Config:DEBUG = FalseDATABASE_URL = 'sqlite:///db.sqlite3'
config = Config()
debug_mode = getattr(config, 'DEBUG', False)
database_url = getattr(config, 'DATABASE_URL', 'default_database_url')# 应用6:与外部库或模块交互
def interact_with_external_module(module_name, attribute_name):module = __import__(module_name)attribute = getattr(module, attribute_name, None)if attribute:# 使用attribute执行操作passelse:print(f"Attribute {attribute_name} not found in module {module_name}")# 应用7:动态类创建
def dynamic_class_factory(class_name, base_class, attribute_dict):class Meta(base_class):passfor name, value in attribute_dict.items():setattr(Meta, name, value)return Meta
attribute_dict = {'my_attribute': 'Hello, world!'}
DynamicClass = dynamic_class_factory('DynamicClass', object, attribute_dict)
instance = DynamicClass()
print(getattr(instance, 'my_attribute'))
# Hello, world!# 应用8:结合装饰器使用
def dynamic_property(func):def wrapper(self, *args, **kwargs):attr_name = '_' + func.__name__if not hasattr(self, attr_name):setattr(self, attr_name, func(self, *args, **kwargs))return getattr(self, attr_name)return wrapper
class MyClass:@dynamic_propertydef expensive_calculation(self):print("Calculating...")return 42
obj = MyClass()
print(obj.expensive_calculation)
print(obj.expensive_calculation)
# <bound method dynamic_property.<locals>.wrapper of <__main__.MyClass object at 0x000002254717D850>>
# <bound method dynamic_property.<locals>.wrapper of <__main__.MyClass object at 0x000002254717D850>>
1-2、VBA:
略,待后补。
2、推荐阅读:

2-1、Python-VBA函数之旅-bytearray()函数

2-2、Python-VBA函数之旅-bytes()函数 

Python算法之旅:Algorithm

Python函数之旅:Functions

个人主页:神奇夜光杯-CSDN博客

http://www.ppmy.cn/ops/3710.html

相关文章

分类算法——模型选择与调优(三)

交叉验证 交叉验证&#xff1a;将拿到的训练数据&#xff0c;分为训练和验证集。以下图为例&#xff1a;将数据分成4份&#xff0c;其中 一份作为验证集。然后经过4次&#xff08;组&#xff09;的测试&#xff0c;每次都更换不同的验证集。即得到4组模型的 结果&#xff0c;取…

深入探索Apache ZooKeeper:关键技术学习与实践指南

导语 Apache ZooKeeper&#xff0c;作为一款广受认可的分布式协调服务&#xff0c;为大型分布式系统提供了强大的数据一致性、服务注册与发现、分布式锁、配置管理等基础服务。本文将深入剖析ZooKeeper的技术内核&#xff0c;梳理其关键学习点&#xff0c;并结合实践场景给出学…

用友U8 CRM swfupload 任意文件上传漏洞复现(XVE-2024-8597)

0x01 免责声明 请勿利用文章内的相关技术从事非法测试&#xff0c;由于传播、利用此文所提供的信息而造成的任何直接或者间接的后果及损失&#xff0c;均由使用者本人负责&#xff0c;作者不为此承担任何责任。工具来自网络&#xff0c;安全性自测&#xff0c;如有侵权请联系删…

关于Zookeeper+Kafka集群

文章目录 一、Zookeeper1、Zookeeper定义2、Zookeeper工作机制3、Zookeeper特点4、Zookeeper数据结构5、Zookeeper应用场景5.1 统一命名服务5.2 统一配置管理5.3 统一集群管理5.4 服务器动态上下线5.5 软负载均衡 6、Zookeeper 选举机制6.1 第一次启动选举机制6.2 非第一次启动…

html2pdf,qrcode库及url参数拼接

概览 此篇文章主要是对html2pdf,qrcode库及url参数拼接的零散整理 一. html2pdf html2pdf 是一个可以将 HTML 内容转换为 PDF 文件的库。它通常用于前端或服务器端&#xff0c;将网页或 HTML 字符串转换为可打印或可分享的 PDF 格式。这对于需要将网页内容保存为 PDF 或者生…

<个人笔记>基础算法模板题

1.基础算法 &#xff08;1&#xff09;一维前缀和 #include<iostream>using namespace std;const int N 1e510;int p[N],res[N]; int n,Q,l,r;int main() {cin >> n >> Q;for(int i 1;i<n;i){cin >> p[i];res[i] res[i - 1] p[i];}while(Q--)…

C#中的Task:异步编程的瑞士军刀

在现代软件开发中&#xff0c;异步编程已经成为处理I/O密集型任务和网络操作的重要手段。C#中的Task是.NET Framework 4.0引入的一个并发编程的抽象&#xff0c;它在后续的.NET Core和.NET 5中得到了进一步的发展和完善。Task代表了一个异步操作&#xff0c;可以等待它的完成&a…

2024五一杯数学建模A题B题C题思路汇总分析

文章目录 1 赛题思路2 比赛日期和时间3 组织机构4 建模常见问题类型4.1 分类问题4.2 优化问题4.3 预测问题4.4 评价问题 5 建模资料 1 赛题思路 (赛题出来以后第一时间在CSDN分享) https://blog.csdn.net/dc_sinor?typeblog 2 比赛日期和时间 报名截止时间&#xff1a;2024…