하얀설표 블로그




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





( 수정됨)


에러

다음과 같이 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







white.seolpyo.com