Base de connaissancesCentre d’examen
FRFrançais
Choisir la langue13

CKTIS / Python

setattr()

Affecte l’attribut nommé par la chaîne et renvoie None.

Version : Python 3.14; repository image, production runtime not attested

Syntaxe

setattr(object, name, value, /)

Affecte l’attribut nommé par la chaîne et renvoie None.

Les règles de __setattr__ et des descripteurs du type s’appliquent. L’emplacement width accepte 7.

L’instance n’a ni dictionnaire ni emplacement height, donc créer height lève AttributeError.

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

Exemples

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__)

Résultat

7
AttributeError

L’instance n’a ni dictionnaire ni emplacement height, donc créer height lève AttributeError.

Sources