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

Python getattr() Function

Python getattr() Function

Python built-in function Python built-in function


Description

getattr() The function returns the value of an object's attribute.

Syntax

getattr syntax:


getattr(object, name[, default])

Parameters

Return Value

Returns the value of the object's attribute.

Example

The following examples demonstrate how to use getattr:

class

A

(

object

)

: ...

bar

=

1

... >>>

a

=

A

(

)

getattr

(

a

,

'

bar

'

)

Get the value of attribute bar

1

getattr

(

a

,

'

bar2

'

)

Attribute bar2 does not exist, raising an exception

Traceback

(

most

recent

call

last

)

:

File

"

"

,

line

1

,

in

<

module

AttributeError

:

'

A

'

object

has

no

attribute

'

bar2

'

getattr

(

a

,

'

bar2

'

,

3

)

Attribute bar2 does not exist, but a default value is set

3

Python built-in function Python built-in function