반응형
작은 파이썬 프로그램을 다음과 같이 정의하면
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
반응형
'파이썬' 카테고리의 다른 글
파이썬 What is actually assertEquals in Python? (0) | 2021.01.12 |
---|---|
파이썬 pandas 그룹의 열에서 개체별로 고유 한 값을 계산하는 방법은 무엇입니까? (0) | 2021.01.12 |
파이썬에서 키로 카운터 정렬 (0) | 2021.01.11 |
파이썬 numpy.genfromtxt를 사용하여 쉼표가 포함 된 문자열이있는 csv 파일 읽기 (0) | 2021.01.11 |
파이썬 Python 스크립트 실행을 어떻게 중단합니까? (0) | 2021.01.11 |
댓글