NoneType 개체에는 Python에서 속성 추가가 없습니다.

Salman Mehmood 2023년6월21일
NoneType 개체에는 Python에서 속성 추가가 없습니다.

이 설명과 함께 NoneType 오류에 대해 알아보고 이 오류가 발생하는 이유를 살펴보겠습니다. 또한 Python에서 이 오류를 수정하는 방법도 배웁니다.

Python에서 AttributeError: NoneType 개체에 속성 추가가 없음 오류 수정

product_list라는 목록을 만들고 이 목록에 몇 가지 항목을 추가한 다음 항목을 하나 더 추가해 보겠습니다. 항목을 확인하면 제대로 작동하지만 product_listNone을 할당한 다음 이 목록에 항목을 추가하려고 하면 NoneType 오류가 발생합니다.

>>> product_list=['x1','x2']
>>> product_list.append('x3')
>>> product_list
['x1', 'x2', 'x3']
>>> product_list=None
>>> product_list.append('x4')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'append'

이는 product_listNoneType이기 때문에 항목을 추가하기 위해 이 개체에 액세스할 수 없으며 다음 명령을 사용하여 이 개체 유형을 확인할 수 있습니다.

>>> type(product_list)
<class 'NoneType'>

이 오류가 발생하는 데는 여러 가지 이유가 있을 수 있습니다. 그중 하나는 목록 안에 항목을 추가하고 새 항목을 추가하는 목록 변수에 저장하려고 할 때입니다.

따라서 다음에 새 항목을 추가하려고 하면 Nonetype 오류가 되는 오류가 발생합니다.

>>> product_list=product_list.append('x3')
>>> product_list.append('x4')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'append'

속성은 추가할 수 있을 뿐만 아니라 다른 개체에 액세스하여 이 오류를 얻을 수도 있습니다. 이 오류(‘NoneType’ 객체에 ‘xyz’ 속성이 없음)가 표시되면 xyz 속성이 객체에 존재하지 않는 것입니다.

액세스하려는 객체가 존재하는지 여부를 dir()을 사용하여 확인할 수 있습니다. append() 속성은 이 목록 내에 존재하지 않습니다.

>>> dir(product_list)
['__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

어떤 이유로든 Python에서는 AttributeError가 발생합니다. 공식 문서를 다시 확인하여 수행하려는 작업이 존재하는지 확인할 수 있습니다. 때때로 Python 스크립트를 작성할 때 Python 규칙에 위배될 수 있습니다. 그래서 이런 종류의 오류가 발생합니다.

Salman Mehmood avatar Salman Mehmood avatar

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