Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python setattr() Function

Python setattr() Function

Python built-in function Python built-in function


Description

setattr() The corresponding function getattr(), used to set the value of an attribute, which does not necessarily already exist.

Syntax

setattr() syntax:


setattr(object, name, value)

Parameters

Return Value

none.

Example

The following examples demonstrate how to use the setattr() function:

Assigning 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 the value:

class

A

(

)

: ...

name

=

"

runoob

"

... >>>

a

=

A

(

)

setattr

(

a

,

"

age

"

,

28

)

print

(

a

.

age

)

28

Python built-in function Python built-in function