다음 오류로 인해 super()가 실패합니다.상위 항목이 개체에서 상속되지 않은 경우 TypeError "인수 1은 classobj가 아닌 유형이어야 합니다"
알 수 없는 오류가 발생했습니다.내 샘플 코드에 무슨 문제가 있는지 알아?
class B:
def meth(self, arg):
print arg
class C(B):
def meth(self, arg):
super(C, self).meth(arg)
print C().meth(1)
나는 '슈퍼' 빌트인 방식의 도움을 받아 샘플 테스트 코드를 받았습니다.
다음은 오류입니다.
Traceback (most recent call last):
File "./test.py", line 10, in ?
print C().meth(1)
File "./test.py", line 8, in meth
super(C, self).meth(arg)
TypeError: super() argument 1 must be type, not classobj
참고로 python 자체의 도움말(super)은 다음과 같습니다.
Help on class super in module __builtin__:
class super(object)
| super(type) -> unbound super object
| super(type, obj) -> bound super object; requires isinstance(obj, type)
| super(type, type2) -> bound super object; requires issubclass(type2, type)
| Typical use to call a cooperative superclass method:
| class C(B):
| def meth(self, arg):
| super(C, self).meth(arg)
|
문제는 클래스 B가 "새로운 스타일의" 클래스로 선언되지 않는다는 것입니다.다음과 같이 변경합니다.
class B(object):
효과가 있을 거야
super()모든 서브클래스/슈퍼클래스는 새로운 스타일의 클래스에서만 작동합니다.항상 그걸 타이핑하는 습관을 들일 것을 권한다.(object)클래스 정의에서 새로운 스타일의 클래스인지 확인합니다.
구식 클래스('클래식' 클래스라고도 함)는 항상 유형입니다.classobj; 새로운 스타일의 클래스는 유형입니다.type이 때문에, 에러 메세지가 표시됩니다.
TypeError: super() argument 1 must be type, not classobj
직접 확인해보십시오.
class OldStyle:
pass
class NewStyle(object):
pass
print type(OldStyle) # prints: <type 'classobj'>
print type(NewStyle) # prints <type 'type'>
Python 3.x에서는 모든 클래스가 새로운 스타일입니다.이전 형식의 클래스에서 구문을 계속 사용할 수 있지만 새 형식의 클래스를 얻을 수 있습니다.따라서 Python 3.x에서는 이 문제가 발생하지 않습니다.
또한 클래스 B를 변경할 수 없는 경우 여러 상속을 사용하여 오류를 수정할 수 있습니다.
class B:
def meth(self, arg):
print arg
class C(B, object):
def meth(self, arg):
super(C, self).meth(arg)
print C().meth(1)
python 버전이 3.X라면 괜찮습니다.
당신의 python 버전은 2.X라고 생각합니다만, 이 코드를 추가하면 슈퍼가 동작합니다.
__metaclass__ = type
그래서 암호는
__metaclass__ = type
class B:
def meth(self, arg):
print arg
class C(B):
def meth(self, arg):
super(C, self).meth(arg)
print C().meth(1)
python 2.7을 사용했을 때도 문제가 있었습니다.python 3.4에서는 매우 잘 동작하고 있습니다.
python 2.7에서 동작하도록 하기 위해, 저는 다음 명령어를 추가했습니다.__metaclass__ = type제 프로그램의 최상위에 속했고, 효과가 있었어요.
__metaclass__: 구식 수업과 신식 수업의 전환을 용이하게 합니다.
언급URL : https://stackoverflow.com/questions/1713038/super-fails-with-error-typeerror-argument-1-must-be-type-not-classobj-when
'programing' 카테고리의 다른 글
| 데이터 프레임의 열을 정규화하다 (0) | 2022.09.29 |
|---|---|
| Jackson을 사용하여 어레이에 대한 JSON 문자열을 해석하는 방법 (0) | 2022.09.29 |
| URI의 마지막 경로세그먼트를 취득하는 방법 (0) | 2022.09.29 |
| python에서 문자열을 구분 기호로 분할합니다. (0) | 2022.09.27 |
| MySQL/Mariadb 문제: "Group by" 앞에 "Order by DESC"가 표시됨 (0) | 2022.09.27 |