CKTIS / Python
setattr()
Wijst het door tekst benoemde attribuut toe en geeft None terug.
Versie: Python 3.14; repository image, production runtime not attested
Syntax
setattr(object, name, value, /)Wijst het door tekst benoemde attribuut toe en geeft None terug.
De regels van __setattr__ en van de descriptors van het type gelden. Het slot width accepteert 7.
Omdat de instantie geen woordenboek of slot height heeft, veroorzaakt het maken van height AttributeError.
class Box:
__slots__ = ("width",)
b = Box()
assert setattr(b, "width", 7) is None and b.width == 7
Voorbeelden
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__)
Resultaat
7 AttributeError
Omdat de instantie geen woordenboek of slot height heeft, veroorzaakt het maken van height AttributeError.