CKTIS / Python
setattr()
Atribui o atributo indicado pela cadeia e devolve None.
Versão: Python 3.14; repository image, production runtime not attested
Sintaxe
setattr(object, name, value, /)Atribui o atributo indicado pela cadeia e devolve None.
Aplicam-se __setattr__ e as regras dos descritores do tipo. O espaço width aceita 7.
Como a instância não tem dicionário nem espaço height, criar height gera AttributeError.
class Box:
__slots__ = ("width",)
b = Box()
assert setattr(b, "width", 7) is None and b.width == 7
Exemplos
class Box:
__slots__ = ("width",)
box = Box()
setattr(box, "width", 7)
print(box.width)
try:
setattr(box, "height", 8)
except AttributeError as error:
print(type(error).__name__)
Resultado
7 AttributeError
Como a instância não tem dicionário nem espaço height, criar height gera AttributeError.