WissensdatenbankPrüfungszentrum
DEDeutsch
Sprache wählen13

CKTIS / Python

setattr()

Setzt das per Zeichenkette benannte Attribut und liefert None.

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

Syntax

setattr(object, name, value, /)

Setzt das per Zeichenkette benannte Attribut und liefert None.

Es gelten __setattr__ und die Deskriptorregeln des Typs. Der Slot width nimmt 7 an.

Da die Instanz weder Wörterbuch noch Slot height besitzt, löst das Anlegen von height AttributeError aus.

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

Beispiele

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

Ergebnis

7
AttributeError

Da die Instanz weder Wörterbuch noch Slot height besitzt, löst das Anlegen von height AttributeError aus.

Quellen