본문 바로가기
개발/Python3

python3 - hasattr() 함수를 알아보자.

by Devsong26 2021. 6. 12.

파이썬3에서 객체의 특정 속성이 존재하는지 확인하고 싶은 경우가 있었다.

찾아보니 hasattr()이라는 함수로 속성 체크 로직을 구현한다고 한다.

 

확인해보자.

 

hasattr()

파이썬의 빌트인 함수이며 상세 설명은 아래와 같다.

hasattr(object, name)
The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)

https://docs.python.org/3/library/functions.html#hasattr

즉, 속성이름을 파라미터로 주었을 때, 객체에 속성이 존재할 경우 True, 아닐 경우 False를 반환한다.

 

예시

class clazz:
    a = "1"
    b = "2"
    c = "3"
    _u = "4"
    __uu = "5"
    
instance = clazz()
print(hasattr(instance, "a")) # True
print(hasattr(instance, "b")) # True
print(hasattr(instance, "c")) # True
print(hasattr(instance, "_u")) # True
print(hasattr(instance, "__uu")) # False

(참고: hasattr()의 객체 파라미터로 self도 넣을 수 있음)

확인해보면 속성으로 정의한 a, b, c, _u는 hasattr()을 호출할 경우 True를 반환하지만, __uu는 속성으로 정의했음에도 불구하고 False를 반환한다. 

 

왜 그럴까?

 

같은 고민을 하던 사람이 있어 stackoverflow에서 해답을 찾을 수 있었다.

Double underscore attribute names invoke "name mangling", so e.g. __hp becomes _Avatar__hp (see e.g. the style guide on inheritance).

https://stackoverflow.com/questions/30209102/hasattr-keeps-returning-false

더블스코어 속성의 이름은 "name mangling"으로 호출이 된다고 한다.

 

name mangling이란? 

In compiler construction, name mangling (also called name decoration) is a technique used to solve various problems caused by the need to resolve unique names for programming entities in many modern programming languages.

https://en.wikipedia.org/wiki/Name_mangling

 

stackoverflow에 답변을 참고하여 아래와 같이 더블 언더스코어 hasattr() 코드 부분을 변경하였고,

True가 반환되는 것을 확인할 수 있다.

class clazz:
    a = "1"
    b = "2"
    c = "3"
    _u = "4"
    __uu = "5"
    
instance = clazz()
print(hasattr(instance, "_clazz__uu"))

 


더 많은 내용을 보시려면 아래를 참고하세요.


Reference

https://docs.python.org/3/library/functions.html#hasattr

 

Built-in Functions — Python 3.9.5 documentation

Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order. abs(x) Return the absolute value of a number. The argument may be an integer, a floating poin

docs.python.org

https://stackoverflow.com/questions/30209102/hasattr-keeps-returning-false

 

hasattr keeps returning False

class Avatar: def __init__(self, HP=100, damage=10, defends=10, magic=5): self.__hp = HP self.__dam = damage self.__def = defends self.__mag = magic def

stackoverflow.com

https://stackoverflow.com/questions/7456807/python-name-mangling

 

Python name mangling

In other languages, a general guideline that helps produce better code is always make everything as hidden as possible. If in doubt about whether a variable should be private or protected, it's bet...

stackoverflow.com

https://en.wikipedia.org/wiki/Name_mangling

 

Name mangling - Wikipedia

This article is about name mangling in computer languages. For name mangling in file systems, see filename mangling. For other uses, see Name conflict. In compiler construction, name mangling (also called name decoration) is a technique used to solve vario

en.wikipedia.org