CKTIS / Python
setattr()
Assegna l’attributo indicato dalla stringa e restituisce None.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
setattr(object, name, value, /)Assegna l’attributo indicato dalla stringa e restituisce None.
Si applicano __setattr__ e le regole dei descrittori del tipo. Lo slot width accetta 7.
L’istanza non ha dizionario né slot height e creare height solleva AttributeError.
class Box:
__slots__ = ("width",)
b = Box()
assert setattr(b, "width", 7) is None and b.width == 7
Esempi
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__)
Risultato
7 AttributeError
L’istanza non ha dizionario né slot height e creare height solleva AttributeError.