Python:属性错误
在每种编程语言中,如果我们开发新程序,很可能会出现错误或异常。这些错误会导致程序未执行。 Python中最常发生的错误之一是“AttributeError”。 AttributeError 可以定义为属性引用或分配失败时引发的错误。
例如,如果我们取一个变量 x,我们被分配一个值 10。在这个过程中,假设我们想要将另一个值附加到该变量。这是不可能的。因为变量是整数类型,所以不支持 append 方法。所以在这类问题中,我们会得到一个名为“AttributeError”的错误。假设如果变量是列表类型,那么它支持 append 方法。那么就没有问题,也没有得到“属性错误”。
注意: Python中的属性错误通常在进行无效属性引用时引发。
有一些机会获得 AttributeError。
示例 1:
Python3
# Python program to demonstrate
# AttributeError
X = 10
# Raises an AttributeError
X.append(6)
Python3
# 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)
Python3
# Python program to demonstrate
# AttributeError
class Geeks():
def __init__(self):
self.a = 'GeeksforGeeks'
# Driver's code
obj = Geeks()
print(obj.a)
# Raises an AttributeError as there
# is no attribute b
print(obj.b)
Python3
# Python program to demonstrate
# AttributeError
class Geeks():
def __init__(self):
self.a = 'GeeksforGeeks'
# 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")
输出:
Traceback (most recent call last):
File "/home/46576cfdd7cb1db75480a8653e2115cc.py", line 5, in
X.append(6)
AttributeError: 'int' object has no attribute 'append'
示例 2:有时拼写的任何变化都会导致属性错误,因为Python是区分大小写的语言。
Python3
# 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。
Python3
# Python program to demonstrate
# AttributeError
class Geeks():
def __init__(self):
self.a = 'GeeksforGeeks'
# Driver's code
obj = Geeks()
print(obj.a)
# Raises an AttributeError as there
# is no attribute b
print(obj.b)
输出:
GeeksforGeeks
错误:
Traceback (most recent call last):
File "/home/373989a62f52a8b91cb2d3300f411083.py", line 17, in
print(obj.b)
AttributeError: 'Geeks' object has no attribute 'b'
属性错误的解决方案
Python中的错误和异常可以使用异常处理来处理,即在Python中使用 try 和 except。
示例:考虑上面的类示例,我们想做其他事情,而不是在引发 AttributeError 时打印回溯。
Python3
# Python program to demonstrate
# AttributeError
class Geeks():
def __init__(self):
self.a = 'GeeksforGeeks'
# 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")
输出:
GeeksforGeeks
There is no such attribute
注意:要了解有关异常处理的更多信息,请单击此处。