Python setattr() Function

Python 内置函数Python Built-in Functions


Description

setattr()function corresponds to functiongetattr(), used to set the attribute value, which does not necessarily exist.

Syntax

setattr() syntax:

setattr(object, name, value)

Parameters

  • object -- Object.
  • name -- String, object attribute.
  • value -- Attribute value.

Return Value

None.

Examples

The following example demonstrates the usage of the setattr() function:

Assign a value to an existing attribute:

>>>class A(object): ... bar = 1 ... >>> a = A() >>> getattr(a, 'bar') # Get the value of attribute bar 1 >>> setattr(a, 'bar', 5) # Set the value of attribute bar >>> a.bar 5

If the attribute does not exist, a new object attribute is created and assigned a value:

>>>class A(): ... name = "example" ... >>> a = A() >>> setattr(a, "age", 28) >>> print(a.age) 28 >>>

Python 内置函数Python Built-in Functions

Other Extensions