Basic Python

getattr

Naranjito 2023. 11. 15. 19:03
  • getattr

It returns the value of the named attribute of an object.

getattr(object, name)
class Person:
    age = 23
    name = "Adam"

person = Person()
getattr(person, 'age')
>>>
23

 

 

When the named attribute is not found, default value is returned.

getattr(object, name, default)
class Person:
    age = 23
    name = "Adam"

person = Person()
getattr(person, 'gender','unknown')
>>>
unknown

The named attribute gender is not present in the class Person. So when calling getattr() with a default value 'unknown', it returns 'unknown'.

 

https://www.programiz.com/python-programming/methods/built-in/getattr

'Basic Python' 카테고리의 다른 글

Logger, Handler, Filter, Formatter  (0) 2023.12.08
str VS repr  (0) 2023.11.16
sort VS sorted  (0) 2023.11.10
abspath, chdir, basename, os.path.join  (0) 2023.11.07
glob  (0) 2023.11.04