Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / Python

setattr()

Asigna el atributo nombrado por la cadena y devuelve None.

Versión: Python 3.14; repository image, production runtime not attested

Sintaxis

setattr(object, name, value, /)

Asigna el atributo nombrado por la cadena y devuelve None.

Se aplican __setattr__ y las reglas de descriptores del tipo. El espacio width acepta 7.

Como la instancia no tiene diccionario ni espacio height, crear height provoca AttributeError.

class Box:
    __slots__ = ("width",)
b = Box()
assert setattr(b, "width", 7) is None and b.width == 7

Ejemplos

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 la instancia no tiene diccionario ni espacio height, crear height provoca AttributeError.

Fuentes