Special Method Protocols

__setattr__() — attributes protocol

Intercept attribute assignment. Delegate to object.__setattr__ for ordinary storage instead of assigning the same attribute recursively. Raise a useful exception for invalid input.

Formal Syntax & Structure

python syntaxpython
def __setattr__(self, name, value):

Parameters & Attributes

NameTypeDescription
namestrAttribute name.
valueobjectAssigned value.

Return Value

None

No meaningful assignment result.

Working Example

Example Snippetpython
class Config:    def __setattr__(self, name, value):        if name == "port" and not 0 < value < 65536: raise ValueError("port")        object.__setattr__(self, name, value)
def demo():    c=Config(); c.port=443    return c.portprint(demo())
Python Reference