En cualquier lenguaje de programación, si desarrollamos nuevos programas, existe una alta probabilidad de obtener errores o excepciones. Estos errores provocan que el programa no se ejecute. Uno de los errores que más se produce en Python es AttributeError. AttributeError se puede definir como un error que se genera cuando falla una referencia o asignación de atributo.
Por ejemplo, si tomamos una variable x se nos asigna un valor de 10. En este proceso supongamos que queremos agregar otro valor a esa variable. No es posible. Debido a que la variable es de tipo entero, no admite el método de adición. Entonces, en este tipo de problema, obtenemos un error llamado AttributeError. Supongamos que si la variable es de tipo lista, entonces admite el método de agregar. Entonces no hay problema y no aparece el error de atributo.
Nota: Los errores de atributos en Python generalmente surgen cuando se hace una referencia de atributo no válida.
Hay algunas posibilidades de que se produzca AttributeError.
Ejemplo 1:
Python3
# Python program to demonstrate> # AttributeError> X>=> 10> # Raises an AttributeError> X.append(>6>)> |
>
>
Producción:
Traceback (most recent call last): File '/home/46576cfdd7cb1db75480a8653e2115cc.py', line 5, in X.append(6) AttributeError: 'int' object has no attribute 'append'>
Ejemplo 2: A veces, cualquier variación en la ortografía provocará un error de atributo, ya que Python distingue entre mayúsculas y minúsculas.
Python3
abstracción en java
# 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)> |
>
>
Producción:
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'> Ejemplo 3 : AttributeError también se puede generar para una clase definida por el usuario cuando el usuario intenta hacer una referencia de atributo no válida.
Python3
# 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)> |
>
agregar en matriz java
>
Producción:
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'>
Ejemplo 4: AttributeError también se puede generar para una clase definida por el usuario cuando el usuario no puede agregar tabulaciones o espacios entre sus líneas de código.
Python3
#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()> |
>
>
Producción:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in ---->1 d.getkeys() AttributeError: el objeto 'dict_parsing' no tiene atributo 'getkeys'>
Error:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in ---->1 d.getkeys() AttributeError: el objeto 'dict_parsing' no tiene atributo 'getkeys'>
Solución para error de atributo
Los errores y excepciones en Python se pueden manejar mediante el manejo de excepciones, es decir, usando try y except en Python.
Ejemplo: Considere el ejemplo de clase anterior, queremos hacer algo más en lugar de imprimir el rastreo cada vez que se genera un AttributeError.
Python3
# 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'>)> |
>
índice de lista
>
Producción:
techcodeview.com There is no such attribute>
Nota: Para saber más sobre el manejo de excepciones, haga clic aquí.