본문 바로가기
Python IDLE

파이썬 메직 메서드

by 자동매매 2023. 3. 30.

파이썬 메직 메서드

1. 객체 속성관련 - getattr, setattr, hasattr, delattr

 

1) getattr 메서드 -  속성의 값 반환 (지정 속성이 미 존재시 반환할 값 설정)

class Employee:
    comp = "Amazon"
    age = 30
    address = 'seoul'
    
    def __getattr__(self,attr_name:str):
        """ attr_name에 전달된 속성이 존재하지 않을 시 반환할 값 지정
            attr_name type은 꼭 str이다.
        """
        return attr_name + ' is not exist.'    


e = Employee()

print(e.age)      # 30
print(e.emp_age)  # emp_age is not exist.

 

다른 방식의 적용

getattr(object, attribute_name, [default])

class Employee:
    comp = "Amazon"
    age = 30
    default_age = 25    
    address = 'seoul'

e = Employee()

print(getattr(e, 'age'))                         # 30
print(getattr(e, 'emp_age', "Not exists"))       # Not exists
print(getattr(e, 'emp_age_other', e.default_age))# 25

 

2) setattr 메서드 -  지정 속성의 값 할당 방식 설정

class Employee:
    comp = "Amazon"
    age = 30
    address = 'seoul'

    def __getattr__(self, attr_name: str):
        """ attr_name에 전달된 속성이 존재하지 않을 시 반환할 값 지정
            attr_name type은 꼭 str이다.
        """
        return attr_name + ' is not exists.'
    
    def __setattr__(self, name: str, value) -> None:
        self.__dict__[name] = value + 1000

e = Employee()

e.age = 10
print(e.age)      # 1010

 

다른 방식의 적용

setattr(object, attribute_name, value)

setattr(e, 'age', 100)                           # e.age = 100
print(getattr(e,'age'))                          # 100

 

3) setattr 메서드 -  속성 존재 여부 확인

hasattr(object, attribute_name)

e = Employee()
print(hasattr(e,'age')) #True

 

4) delattr 메서드 - 속성 삭제

delattr(object, attribute_name)

 

5) dir(object) 명령어

object의 전체 attribute를 확인할 수 있습니다

 

## 참조 ##

  • __getattribute__는 (해당 attribute가 있든 없든) 가장 “선순위”로 호출되고,
  • __getattr__는 (해당 attribute를 찾을 수 없을경우) 가장 “후순위”로 호출된다.
class Employee:
    comp = "Amazon"
    age = 30
    address = 'seoul'

    def __getattr__(self, attr_name: str):
        """ attr_name에 전달된 속성이 존재하지 않을 시 반환할 값 지정
            attr_name type은 꼭 str이다.
        """
        return attr_name + ' is not exists.'
    
    def __getattribute__(self, attr_name: str):
        """ attr_name에 전달된 속성이 존재하지 않을 시 반환할 값 지정
            attr_name type은 꼭 str이다.
        """
        return attr_name + ' IS NOT EXISTS.'

e = Employee()
print(e.age)  # age IS NOT EXISTS.

 

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

Jupyter notebook  (0) 2022.04.02
requirements.txt로 패키지 관리하기  (0) 2022.03.13
가상환경 만들기  (0) 2022.03.13
python 패키지 설치 _ setup.py 이용  (0) 2022.02.19

댓글