CKTIS / Python
setattr()
Nastaví atribut pojmenovaný řetězcem a vrátí None.
Verze: Python 3.14; repository image, production runtime not attested
Syntaxe
setattr(object, name, value, /)Nastaví atribut pojmenovaný řetězcem a vrátí None.
Platí pravidla __setattr__ a deskriptorů typu. Slot width přijme 7.
Instance nemá slovník ani slot height, a proto vytvoření height vyvolá AttributeError.
class Box:
__slots__ = ("width",)
b = Box()
assert setattr(b, "width", 7) is None and b.width == 7
Příklady
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__)
Výsledek
7 AttributeError
Instance nemá slovník ani slot height, a proto vytvoření height vyvolá AttributeError.