모든 프로그래밍 언어에서 새로운 프로그램을 개발하면 오류나 예외가 발생할 가능성이 높습니다. 이러한 오류로 인해 프로그램이 실행되지 않습니다. Python에서 가장 많이 발생하는 오류 중 하나는 AttributeError입니다. AttributeError는 속성 참조 또는 할당이 실패할 때 발생하는 오류로 정의할 수 있습니다.
예를 들어 변수 x를 사용하면 값 10이 할당됩니다. 이 프로세스에서 해당 변수에 다른 값을 추가한다고 가정합니다. 불가능합니다. 변수가 정수 유형이므로 추가 방법을 지원하지 않습니다. 따라서 이러한 유형의 문제에서는 AttributeError라는 오류가 발생합니다. 변수가 목록 유형인 경우 추가 방법을 지원한다고 가정합니다. 그러면 문제가 없으며 gettingAttribute 오류도 발생하지 않습니다.
메모: Python의 속성 오류는 일반적으로 잘못된 속성 참조가 이루어질 때 발생합니다.
AttributeError가 발생할 가능성이 몇 가지 있습니다.
예시 1:
파이썬3
xd xd 의미
# Python program to demonstrate> # AttributeError> X>=> 10> # Raises an AttributeError> X.append(>6>)> |
>
>
산출:
Traceback (most recent call last): File '/home/46576cfdd7cb1db75480a8653e2115cc.py', line 5, in X.append(6) AttributeError: 'int' object has no attribute 'append'>
예 2: Python은 대소문자를 구분하는 언어이므로 철자의 변형으로 인해 속성 오류가 발생하는 경우가 있습니다.
파이썬3
# Python program to demonstrate> # AttributeError> # Raises an AttributeError as there is no> # method as fst for strings> string>=> 'The famous website is { }'>.fst(>'geeksforgeeks'>)> print>(string)> |
>
미세석핵
>
산출:
Traceback (most recent call last): File '/home/2078367df38257e2ec3aead22841c153.py', line 3, in string = 'The famous website is { }'.fst('geeksforgeeks') AttributeError: 'str' object has no attribute 'fst'> 실시예 3 : 사용자가 잘못된 특성 참조를 만들려고 하면 사용자 정의 클래스에 대해 AttributeError가 발생할 수도 있습니다.
파이썬3
# Python program to demonstrate> # AttributeError> class> Geeks():> > >def> __init__(>self>):> >self>.a>=> 'techcodeview.com'> > # Driver's code> obj>=> Geeks()> print>(obj.a)> # Raises an AttributeError as there> # is no attribute b> print>(obj.b)> |
>
>
산출:
techcodeview.com>
오류:
목록 인덱스
Traceback (most recent call last): File '/home/373989a62f52a8b91cb2d3300f411083.py', line 17, in print(obj.b) AttributeError: 'Geeks' object has no attribute 'b'>
예시 4: 사용자가 코드 줄 사이에 탭이나 공백을 추가하지 못한 경우 사용자 정의 클래스에 대해 AttributeError가 발생할 수도 있습니다.
파이썬3
#This is a dictionary parsing code written by Amit Jadhav> #Because of an Indentation Error you will experience Attribute Error> class> dict_parsing:> > >def> __init__(>self>,a):> >self>.a>=> a> > >def> getkeys(>self>):> >if> self>.notdict():> >return> list>(>self>.a.keys())> > >def> getvalues(>self>):> >if> self>.notdict():> >return> list>(>self>.a.values())> > >def> notdict(>self>):> >if> type>(>self>.a) !>=> dict>:> >raise> Exception(>self>,a,>'not a dictionary'>)> >return> 1> > >def> userinput(>self>):> >self>.a>=> eval>(>input>())> >print>(>self>.a,>type>(>self>.a))> >print>(>self>.getykeys())> >print>(>self>.getvalyes())> > >def> insertion(>self>,k,v):> >self>.a[k]>=>v> > d>=> dict_parsing({>'k1'>:>'amit'>,>'k2'>:[>1>,>2>,>3>,>4>,>5>]})> d.getkeys()> |
>
>
산출:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in ---->1 d.getkeys() AttributeError: 'dict_parsing' 객체에 'getkeys'>'> 속성이 없습니다.오류:
'> 속성이 없습니다. AttributeError에 대한 솔루션
Python의 오류 및 예외는 예외 처리를 사용하여 처리할 수 있습니다. 즉, Python에서 try 및 Except를 사용합니다.
예: 위의 클래스 예제를 고려하면 AttributeError가 발생할 때마다 역추적을 인쇄하는 대신 다른 작업을 수행하고 싶습니다.
파이썬3
데이터 프레임을 만드는 팬더
# Python program to demonstrate> # AttributeError> class> Geeks():> > >def> __init__(>self>):> >self>.a>=> 'techcodeview.com'> # Driver's code> obj>=> Geeks()> # Try and except statement for> # Exception handling> try>:> >print>(obj.a)> > ># Raises an AttributeError> >print>(obj.b)> > # Prints the below statement> # whenever an AttributeError is> # raised> except> AttributeError:> >print>(>'There is no such attribute'>)> |
>
산출:
techcodeview.com There is no such attribute>
메모: 예외 처리에 대한 자세한 내용을 보려면 여기를 클릭하세요.