在 Python 中,setattr()函数用于动态设置对象的属性值;

函数语法

setattr(object, name, value)

参数:

  • object:要设置属性的对象;
  • name:属性名称;
  • value:要设置的属性值;

如果对象已经存在具有相同名称的属性,则该属性的值将被覆盖;

setattr()函数只能用于设置对象的属性或类的属性,而不能用于设置模块的属性或内置类型的属性。

setattr() 函数示例

最基本的用法:

class Person:
    pass

p = Person()
setattr(p, 'age', 30)
print(p.age)   # 30

常用于动态的设置属性:

class Config:
    pass

cfg = Config()

attributes = {
    'host': 'localhost',
    'port': 8080,
    'timeout': 30
}

for key, value in attributes.items():
    setattr(cfg, key, value)

print(cfg.host)     # localhost
print(cfg.port)     # 8080
print(cfg.timeout)  # 30

动态的创建类并设置属性:

def create_dynamic_class(class_name, **kwargs):

    DynamicClass = type(class_name, (), {})

    instance = DynamicClass()

    for key, value in kwargs.items():
        setattr(instance, key, value)
    
    return instance

cfg = create_dynamic_class(
    'Config',
    host='localhost',
    port='8080',
    timeout=30
)

print(type(cfg))  # <class '__main__.Config'>
print(cfg.host)   # localhost
print(cfg.port)   # 8080
print(cfg.timeout) # 30