logo

Python: AttributeError

En tots els llenguatges de programació, si desenvolupem programes nous, hi ha una gran probabilitat d'obtenir errors o excepcions. Aquests errors donen lloc a que el programa no s'executa. Un dels errors que es produeix principalment a Python és AttributeError. AttributeError es pot definir com un error que es produeix quan falla una referència d'atribut o una assignació.
Per exemple, si prenem una variable x se'ns assigna un valor de 10. En aquest procés suposem que volem afegir un altre valor a aquesta variable. No és possible. Com que la variable és un tipus enter, no admet el mètode append. Per tant, en aquest tipus de problemes, obtenim un error anomenat AttributeError. Suposem que si la variable és de tipus llista, admet el mètode append. Aleshores no hi ha cap problema i no s'obté un error d'Atribut.

Nota: Els errors d'atribut a Python es generen generalment quan es fa una referència d'atribut no vàlida.
Hi ha algunes possibilitats d'obtenir AttributeError.
Exemple 1:



Python 3






# Python program to demonstrate> # AttributeError> X>=> 10> # Raises an AttributeError> X.append(>6>)>



>

>

Sortida:

Traceback (most recent call last): File '/home/46576cfdd7cb1db75480a8653e2115cc.py', line 5, in X.append(6) AttributeError: 'int' object has no attribute 'append'>

Exemple 2: De vegades, qualsevol variació en l'ortografia provocarà un error d'atribut, ja que Python és un llenguatge sensible a majúscules i minúscules.

Python 3


c estructura en estructura



# 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)>

>

>

Sortida:

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'>

Exemple 3 : AttributeError també es pot generar per a una classe definida per l'usuari quan l'usuari intenta fer una referència d'atribut no vàlida.

Python 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)>

>

conjunt vs mapa
>

Sortida:

techcodeview.com>

Error:

Traceback (most recent call last): File '/home/373989a62f52a8b91cb2d3300f411083.py', line 17, in print(obj.b) AttributeError: 'Geeks' object has no attribute 'b'>

Exemple 4: AttributeError també es pot generar per a una classe definida per l'usuari quan l'usuari no afegeix tabulacions o espais entre les seves línies de codi.

Python 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()>

>

>

Sortida:

--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in ---->1 d.getkeys() AttributeError: l'objecte 'dict_parsing' no té cap atribut 'getkeys'>

Error:

--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in ---->1 d.getkeys() AttributeError: l'objecte 'dict_parsing' no té cap atribut 'getkeys'>

Solució per a AttributeError

Els errors i les excepcions a Python es poden gestionar mitjançant la gestió d'excepcions, és a dir, utilitzant try i excepte a Python.

Exemple: Penseu en l'exemple de classe anterior, volem fer una altra cosa en lloc d'imprimir el rastreig sempre que es produeixi un AttributeError.

Python 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'>)>

>

substituir tot java
>

Sortida:

techcodeview.com There is no such attribute>

Nota: Per obtenir més informació sobre la gestió d'excepcions, feu clic aquí.