TypeError: __str__이 문자열이 아닌 출력을 반환했습니다.
- Python이 문자열이 아닌 오류를 반환했지만 출력 출력
-
TypeError 해결:
__str__
반환된 비 문자열 -
__str__
__repr__()
과 함께 비문자열을 반환했습니다.
이 글은 함수에서 return 문을 사용하지 않고 문자열을 출력하려고 할 때 발생하는 문제를 해결하는 것을 목표로 합니다.
Python이 문자열이 아닌 오류를 반환했지만 출력 출력
다음 코드는 TypeError: __str__
이 비문자열을 반환했지만 여전히 출력을 인쇄합니다.
예제 코드:
class xy:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
print("X={0}, Y={1}")
if __name__ == "__main__":
x_y = xy("value of x is 1", "value of y is 2")
print(x_y)
출력:
TypeError Traceback (most recent call last)
<ipython-input-1-7b40a083df6c> in <module>
10 if __name__ == "__main__":
11 x_y = xy('value of x is 1','value of y is 2')
---> 12 print(x_y)
TypeError: __str__ returned non-string (type NoneType)
오류, 즉 __str__
이 비문자열(유형 NoneType)을 반환하는 이유는 무엇입니까? 먼저 __str__
연산자의 작업을 이해해야 합니다.
__str__
연산자는 주로 문자열을 반환하도록 설계되었지만 주로 문자열을 인쇄하는 데 사용합니다. Python에는 __str__
에 대한 두 가지 용어가 있으며, 연산자 또는 Dunder 메서드와 상호 교환적으로 사용됩니다.
위의 코드에서 __str__
메서드는 print()
함수를 직접 호출하고 문자열을 인쇄하지만 문자열을 반환하지는 않습니다. 위의 오류가 표시되는 이유입니다.
또한 __str__
연산자는 문자열을 인쇄하고 아무것도 반환하지 않습니다. 이것이 오류에서 None을 사용하는 이유입니다.
TypeError 해결: __str__
반환된 비 문자열
__str__
메서드의 return 문을 사용하여 이 문제를 해결할 수 있습니다. 따라서 문자열을 인쇄하는 대신 __str__
메서드에서 문자열을 반환해야 합니다. 다음 코드를 참조하십시오.
예제 코드:
class xy:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return ("X={0}, Y={1}").format(self.x, self.y)
if __name__ == "__main__":
x_y = xy("value of x is 1", "value of y is 2")
print(x_y)
출력:
X=value of x is 1, Y=value of y is 2
위의 코드에는 문제가 하나 더 있습니다. 그리고 문제는 반환하는 값이 문자열이 아닌 경우 정확한 오류를 표시하지만 이번에는 변수 유형이 None
이 아니라는 것입니다.
예제 코드:
class xy:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return 123
if __name__ == "__main__":
x_y = xy("value of x is 1", "value of y is 2")
print(x_y)
출력:
TypeError Traceback (most recent call last)
<ipython-input-9-173c41d63dab> in <module>
12 if __name__ == "__main__":
13 x_y = xy('value of x is 1','value of y is 2')
---> 14 print(x_y)
TypeError: __str__ returned non-string (type int)
이를 해결하려면 값을 타입 변환하고 str()
메서드로 래핑해야 합니다. 즉, str
메서드의 요구 사항이므로 변수의 유형을 문자열로 변환해야 합니다.
예제 코드:
class xy:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return str(123)
if __name__ == "__main__":
x_y = xy("value of x is 1", "value of y is 2")
print(x_y)
출력:
123
이제 코드는 예상되는 모든 문제를 해결하고 str
메서드의 요구 사항을 충족했기 때문에 가능한 모든 경우에 대해 실행됩니다. 즉, 문자열 값만 반환합니다.
__str__
__repr__()
과 함께 비문자열을 반환했습니다.
__repr__()
메서드는 str
메서드와 동일한 작업을 수행합니다. 다음 코드를 참조하십시오.
예제 코드:
class calculate(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
print("(%r, %r, %r)" % (self.x, self.y, self.z))
equation = calculate(1, 2, 3)
print(equation)
출력:
(1, 2, 3)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-0ee74d4c74c8> in <module>
8
9 equation = calculate(1, 2, 3)
---> 10 print(equation)
TypeError: __str__ returned non-string (type NoneType)
위의 코드는 __repr__()
메서드에서 문자열을 반환하는 대신 문자열을 인쇄합니다. 따라서 __repr__()
메서드를 사용하여 문자열을 인쇄하는 대신 return
문을 사용하여 해결할 수 있습니다.
예제 코드:
class calculate(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return str("(%r, %r, %r)" % (self.x, self.y, self.z))
equation = calculate(1, 2, 3)
print(equation)
출력:
(1, 2, 3)
Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.
LinkedIn관련 문장 - Python Error
- AttributeError 수정: Python에서 'generator' 객체에 'next' 속성이 없습니다.
- AttributeError 해결: 'list' 객체 속성 'append'는 읽기 전용입니다.
- AttributeError 해결: Python에서 'Nonetype' 객체에 'Group' 속성이 없습니다.
- AttributeError: 'Dict' 객체에 Python의 'Append' 속성이 없습니다.
- AttributeError: 'NoneType' 객체에 Python의 'Text' 속성이 없습니다.
- AttributeError: Int 객체에 속성이 없습니다.