본문 바로가기
파이썬

파이썬에서 클래스에 대한 클래스 메서드를 동적으로 만드는 방법

by º기록 2021. 1. 12.
반응형

작은 파이썬 프로그램을 다음과 같이 정의하면

class a():
    def _func(self):
        return "asdf"

    # Not sure what to resplace __init__ with so that a.func will return asdf
    def __init__(self, *args, **kwargs):
         setattr(self, 'func', classmethod(self._func))

if __name__ == "__main__":
    a.func

역 추적 오류가 발생합니다.

Traceback (most recent call last):
  File "setattr_static.py", line 9, in <module>
    a.func
AttributeError: class a has no attribute 'func'

내가 알아 내려고하는 것은 객체를 인스턴스화하지 않고 클래스 메서드를 클래스에 동적으로 설정하는 방법입니다.

이 문제에 대한 답은

class a():
    pass

def func(cls, some_other_argument):
    return some_other_argument

setattr(a, 'func', classmethod(func))

if __name__ == "__main__":
    print(a.func)
    print(a.func("asdf"))

다음 출력을 반환합니다.

<bound method type.func of <class '__main__.a'>>
asdf

 

해결 방법

 

클래스 객체에 대한 간단한 할당이나 클래스 객체의 setattr에 의해 클래스에 클래스 메서드를 동적으로 추가 할 수 있습니다. 여기에서는 혼란을 줄이기 위해 클래스가 대문자로 시작하는 파이썬 규칙을 사용하고 있습니다.

# define a class object (your class may be more complicated than this...)
class A(object):
    pass

# a class method takes the class object as its first variable
def func(cls):
    print 'I am a class method'

# you can just add it to the class if you already know the name you want to use
A.func = classmethod(func)

# or you can auto-generate the name and set it this way
the_name = 'other_func' 
setattr(A, the_name, classmethod(func))

 

참조 페이지 https://stackoverflow.com/questions/17929543

 

 

반응형

댓글