웹사이트 검색

파이썬 getattr()


이전 튜토리얼에서 우리는 파이썬 시스템 명령에 대해 배웠습니다. 이 자습서에서는 Python getattr() 함수에 대해 설명합니다.

파이썬 getattr() 함수

Python getattr() 함수는 객체의 속성 값을 가져오는 데 사용되며 해당 객체의 속성이 없으면 기본값이 반환됩니다. 기본적으로 기본값을 반환하는 것이 Python getattr() 함수를 사용해야 하는 주된 이유입니다. 따라서 자습서를 시작하기 전에 Python의 getattr() 함수의 기본 구문을 살펴보겠습니다.

getattr(object_name, attribute_name[, default_value])

파이썬 getattr() 예제

이 섹션에서는 getattr() 함수를 사용하여 객체의 속성 값에 액세스하는 방법에 대해 알아봅니다. Student라는 클래스를 작성한다고 가정합니다. Student 클래스의 기본 속성은 student_idstudent_name입니다. 이제 우리는 Student 클래스의 개체를 만들고 속성에 액세스합니다.

class Student:
    student_id=""
    student_name=""

    # initial constructor to set the values
    def __init__(self):
        self.student_id = "101"
        self.student_name = "Adam Lam"

student = Student()
# get attribute values by using getattr() function
print('\ngetattr : name of the student is =', getattr(student, "student_name"))

# but you could access this like this
print('traditional: name of the student is =', student.student_name)

파이썬 getattr() 기본값

이 섹션에서는 python getattr() 기본값 옵션을 사용합니다. 객체에 속하지 않은 속성에 액세스하려면 getattr() 기본값 옵션을 사용할 수 있습니다. 예를 들어 학생에 대한 student_cgpa 속성이 없으면 기본값이 표시됩니다. 다음 예에서는 기본값의 예를 볼 수 있습니다. 또한 속성이 존재하지 않고 기본값 옵션을 사용하지 않는 경우 어떻게 되는지 알아봅니다.

class Student:
    student_id=""
    student_name=""

    # initial constructor to set the values
    def __init__(self):
        self.student_id = "101"
        self.student_name = "Adam Lam"

student = Student()
# using default value option
print('Using default value : Cgpa of the student is =', getattr(student, "student_cgpa", 3.00))
# without using default value
try:
    print('Without default value : Cgpa of the student is =', getattr(student, "student_cgpa"))
except AttributeError:
    print("Attribute is not found :(")

따라서 코드를 실행하면 다음과 같은 결과가 나타납니다.

Using default value : Cgpa of the student is = 3.0
Attribute is not found :(

getattr() 함수를 호출하는 동안 기본값이 제공되지 않으면 AttributeError가 발생합니다.

Python getattr() 함수를 사용하는 이유

파이썬 getattr()을 사용하는 주된 이유는 속성의 이름을 문자열로 사용하여 값을 얻을 수 있기 때문입니다. 따라서 콘솔에서 프로그램의 속성 이름을 수동으로 입력할 수 있습니다. 다시 말하지만 속성을 찾을 수 없는 경우 일부 기본값을 설정하면 불완전한 데이터 중 일부를 완성할 수 있습니다. 또한 학생 수업이 진행 중인 경우 getattr() 함수를 사용하여 다른 코드를 완성할 수 있습니다. Student 클래스에 이 속성이 있으면 자동으로 선택하고 기본값을 사용하지 않습니다. 이것이 파이썬 getattr() 함수에 관한 전부입니다. 이에 대한 문의 사항이 있으시면 아래 댓글란을 이용해주세요. 참조: 공식 문서