[Python Snippets] Python setattr, getattr, delattr, hasattr

setattr

setattr(object, name, value)

class SampleClass:
    def __init__(self, num):
        self.num = num
>>> instance = SmapleClass(1)
>>> instance.num
1
>>> setattr(instance, 'num', 2)
>>> instance.num
2

기존 속성의 값을 바꾸는 경우

>>> setattr(instance, 'another_num', 5)
>>> instance.another_num
5

getattr

getattr(object, name[, default])

class SampleClass:
    def __init__(self, num):
        self.num = num
>>> instance = SmapleClass(1)
>>> instance.num
1
>>> getattr(instance, 'num')
1

기존 속성의 값을 가져오는 경우

>>> c.x
1

getattr을 사용하지 않고, c.x를 하여도 동일한 결과

>>> getattr(instance, 'not_exist_attr')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-15-d00562231f3e> in <module>
----> 1 getattr(instance, 'not_exist_attr')

AttributeError: 'SampleClass' object has no attribute 'not_exist_attr'

기존에 존재하지 않는 속성을 가져오려 하는 경우(기본 값이 없을 때)

>>> getattr(instance, 'not_exist_attr', 10)
>>> 10

기존에 존재하지 않는 속성을 가져오려 하는 경우(기본 값이 있을 떄)

delattr

delattr(object, name)

class SampleClass:
    def __init__(self, num):
        self.num = num
>>> instance = SmapleClass(1)
>>> instance.num
1
>>> delattr(instance, 'num')

>>> getattr(instance, 'num')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-19-bed1e7fa7976> in <module>
----> 1 getattr(instance, 'num')

AttributeError: 'SampleClass' object has no attribute 'num'

기존 속성을 제거하는 경우

>>> del instance.num

>>> getattr(instance, 'num')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-23-bed1e7fa7976> in <module>
----> 1 getattr(instance, 'num')

AttributeError: 'SampleClass' object has no attribute 'num'

delattr을 사용하지 않고 del c.x를 하여도 동일한 결과를 얻는다.

def greek_comparator(lhs, rhs):
    return cmp(greek_alphabet.index(lhs), greek_alphabet.index(rhs))
>>> delattr(instance, 'not_exist_attr')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-55223dcbb687> in <module>
----> 1 delattr(instance, 'not_exist_attr')

AttributeError: not_exist_attr

기존에 존재하지 않는 속성을 제거하려는 경우

hasattr

hasattr(object, name)

class SampleClass:
    def __init__(self, num):
        self.num = num
>>> instance = SmapleClass(1)
>>> instance.num
1
>>> hasattr(instance, 'num')
True

해당 object에 name 속성이 존재하는 경우

>>> hasattr(instance, 'num')
False

해당 object에 name 속성이 존재하지 않는 경우

REFERENCE