CKTIS / Python
setattr()
Nastaví atribút pomenovaný reťazcom a vráti None.
Verzia: Python 3.14; repository image, production runtime not attested
Syntax
setattr(object, name, value, /)Nastaví atribút pomenovaný reťazcom a vráti None.
Platia pravidlá __setattr__ a deskriptorov typu. Slot width prijme 7.
Inštancia nemá slovník ani slot height, a preto vytvorenie height vyvolá AttributeError.
class Box:
__slots__ = ("width",)
b = Box()
assert setattr(b, "width", 7) is None and b.width == 7
Prí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ýsledok
7 AttributeError
Inštancia nemá slovník ani slot height, a preto vytvorenie height vyvolá AttributeError.