해결)*(class) object has no attribute *(function)

작성자: [관리자] 하얀설표

2023.06.28 16:37 (KST) 작성됨

2023.06.28 16:41 (KST) 수정됨






(2023.06.28) 수정됨.

에러

다음과 같이 class object(객체)에 특정 function(명령어)이 없다는 내용의 에러가 발생할 수 있다.

AttributeError: {class} object has no attribute {function}

 

예시를 보자면 다음과 같다.

1.replace('', '')
>> AttributeError: 'int' object has no attribute 'replace'
1.1.round()
>> AttributeError: 'float' object has no attribute 'round'
'abc'.append(1)
>> AttributeError: 'str' object has no attribute 'append'
{'a': 1}.append()
>> AttributeError: 'dict' object has no attribute 'append'
[1, 2, 3].text()
>> AttributeError: 'list' object has no attribute 'split'
{1, 2, 3}.items()
>> AttributeError: 'set' object has no attribute 'items'
decimal.Decimal('123').decode()
>> AttributeError: 'decimal.Decimal' object has no attribute 'decode'

 

해결방법

각 객체의 type을 확인하여 사용하고자 하는 파이썬 명령어를 사용하는 올바른 type을 대입하면 에러를 해결할 수 있다.
객체 속성은 파이썬의 type 명령어를 통해 확인할 수 있다.

print(type('123'))
>> <class 'str'>

 

if type('123') is str:
    print(True)
else:
    print(False)
>> True

 

해결 예시

replace는 int가 아닌 str 객체에 사용하는 명령어다.

1.replace('', '')
>> '1'.replace('1', '2')

 

round는 인수를 전달해 사용하는 명령어다.

1.1.round()
>> round(1.1)

 

append는 str이나 dict가 아닌 list 객체에 사용하는 명령어다.

'abc'.append(1)
>> ['abc'].append('123')

{'a': 1}.append()
>> [{'a': 1}].append('abc')

 

split은 list가 아닌 str 객체에 사용하는 명령어다.

[1, 2, 3].split()
>> '123'.split('2')

 

items는 set이 아닌 dict 객체에 사용하는 명령어다.

{1, 2, 3}.items()
>> {1: 2, 3: 4, 5: 6}.items()

 

decode는 Decimal이 아닌 str 객체에 사용하는 명령어다.

decimal.Decimal('123').decode()
>> '123'.decode()

 

참고사항

다음과 같이 nonetype object가 나왔다면 대부분 해당 변수값이 None이기 때문에 에러가 발생하는 것이다.

AttributeError: 'nonetype' object has no attribute *






추천 (0)


글 목록

댓글을 달 수 없는 게시물입니다.


"분류없음" 카테고리의 #Python, #에러해결 관련 게시물

분류없음
예제)특정 조합이 리스트 요소에 반드시 포함되어야 한다는 사실만 알 때의 조건식
수정 08.20 | [관리자] 하얀설표
👍 0
#Python, #예제
🗨️ 0
썸네일
분류없음
주식시장 개장일과 휴장일 정보를 간단하게 가져오는 방법(엑셀, 파이썬)
수정 07.20 | [관리자] 하얀설표
👍 0
#Python, #주식
🗨️ 0
분류없음
해결) 장고 bulk_update의 메모리 누수 문제(django orm bluk_update method memory leak)
수정 07.12 | [관리자] 하얀설표
👍 0
#Python, #Django
🗨️ 0
분류없음
해결) django.db.utils.OperationalError: database is locked
수정 06.18 | [관리자] 하얀설표
👍 0
#Python, #에러해결, #Django
🗨️ 0
분류없음
악성 크롤러를 괴롭히는 방법
수정 05.18 | [관리자] 하얀설표
👍 0
#Python, #Django
🗨️ 0
분류없음
장고) 모든 방문자에게 세션 부여하기(anonymous user session)
수정 05.15 | [관리자] 하얀설표
👍 0
#Python, #Django
🗨️ 0
썸네일
분류없음
한국거래소의 수정주가 계산 공식을 알아보자
수정 05.10 | [관리자] 하얀설표
👍 0
#Python, #주식
🗨️ 0
썸네일
분류없음
파이썬으로 연속 조회가 가능한 주식 차트 만들기(tkinter, seolpyo-mplchart)
수정 05.08 | [관리자] 하얀설표
👍 0
#Python
🗨️ 0
썸네일
분류없음
seolpyo-mplchart document
수정 05.08 | [관리자] 하얀설표
👍 0
#Python
🗨️ 0
썸네일
분류없음
seolpyo_mplchart 사용 설명서
수정 05.08 | [관리자] 하얀설표
👍 0
#Python
🗨️ 0