본문 바로가기
카테고리 없음

python hasattr() 함수 정리

by python pro 2023. 2. 10.
반응형

파이썬 내장 함주 중 "hasattr()" 함수는 객체에 특정 속성이 있는지 확인하는 함수입니다.

이 함수는 다음과 같이 사용합니다.

hasattr(object, attribute)

"object"는 속성을 확인하고자 하는 객체입니다. "attribute"는 객체의 속성 이름입니다. 이 함수는 "attribute"가 "object"에 존재하면 True, 그렇지 않으면 False를 반환합니다.

class Person:
  def __init__(self, name):
    self.name = name

person = Person("John")

print(hasattr(person, "name")) # True
print(hasattr(person, "age")) # False

위의 코드에서 "person"이라는 객체는 "name" 속성이 있고, "age" 속성은 없습니다. 그러므로 "hasattr(person, "name")"은 True를 반환하고, "hasattr(person, "age")"은 False를 반환합니다.

 

조금 다른 예제를 정리해봤습니다.

class Customer:
  def __init__(self, name, email):
    self.name = name
    self.email = email

customer = Customer("John", "john@example.com")

# 고객의 정보가 주어졌을 때, email 정보가 있으면 email 주소를 출력하고,
# 그렇지 않으면 "Email information not available"을 출력합니다.
if hasattr(customer, "email"):
  print(customer.email)
else:
  print("Email information not available")

위의 코드에서 "customer" 객체는 "email" 속성을 가지고 있기 때문에 "hasattr(customer, "email")"은 True를 반환합니다. 그러므로 "customer.email"을 출력합니다.

 

 

반응형

댓글