AttributeError: 'str'对象没有'get'属性的解决方法

4,926 阅读3分钟

AttributeError: 'str' object has no attribute 'get' 主要发生在你试图调用get()方法时发生。该属性get()方法存在于字典中,必须在字典数据类型上调用。

在本教程中,我们将看看什么是 AttributeError: 'str' object has no attribute 'get' 以及如何通过实例解决这个错误。

什么是AttributeError: 'str' object has no attribute 'get'?

如果我们调用get()方法,Python 将引发AttributeError: 'str' 对象没有属性 'get'。如果你有一个返回字符串而不是字典的方法,这个错误也可能发生。

让我们举一个简单的例子来重现这个错误。

# Method return string instead of dict
def fetch_data():
    output = "Toyota Car"
    return output


data = fetch_data()
print(data.get("name"))

输出

AttributeError: 'str' object has no attribute 'get'

在上面的例子中,我们有一个方法 fetch_data()返回一个字符串,而不是一个dictionary

由于我们调用get()方法,我们得到了AttributeError

我们也可以检查变量类型是否使用了type()方法,并且使用dir()方法,我们还可以打印一个给定对象的所有属性的列表。

# Method return string instead of dict
def fetch_data():
    output = "Toyota Car"
    return output


data = fetch_data()
print("The type of the object is ", type(data))
print("List of valid attributes in this object is ", dir(data))

输出

The type of the object is  <class 'str'>

List of valid attributes in this object is  ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

如何解决AttributeError: 'str' object has no attribute 'get'?

让我们看看如何解决这个错误。

解决方案1 - 在有效的字典上调用get()方法

我们可以通过调用 get()方法来解决这个错误,在有效的字典对象上调用这个方法,而不是字符串类型。

dict.get()方法返回给定键的值。该 get()方法不会抛出KeyError(如果键不存在);相反,我们会得到 None值或我们在方法中传递的默认值。 get()方法中传递的值或默认值。

# Method returns dict
def fetch_data():
    output = {"Name": "Audi", "Release_Date": "2022", "Price": "$45000"}
    return output

data = fetch_data()

# Get the  car Name
print(data.get("Name"))

输出

Audi

解决方案 2 - 使用 type 检查对象是否是 dictionary 类型的

另一种方法是检查对象是否为 dictionary 类型;我们可以用 type()方法来做。这样,我们就可以在调用方法之前检查对象的数据类型是否正确。 get()方法。

# Method returns dict
def fetch_data():
    output = {"Name": "Audi", "Release_Date": "2022", "Price": "$45000"}
    return output


adata = fetch_data()

# Check if the object is dict
if (type(data) == dict):
    print(data.get("Name"))


softwares = "Norton, Bit Defender"

if (type(softwares) == dict):
    print(softwares.get("Name"))
else:
    print("The object is not dictionary and it is of type ", type(softwares))

输出

Audi
The object is not dictionary and it is of type  <class 'str'>

解决方案 3 - 使用 hasattr 检查该对象是否有 get 属性

在调用 get()方法之前,我们还可以检查对象是否具有某种属性。即使我们调用一个返回不同数据的外部API,使用 hasattr()方法,我们可以检查该对象是否有一个给定名称的属性。

# Method returns dict
def fetch_data():
    output = {"Name": "Audi", "Release_Date": "2022", "Price": "$45000"}
    return output


data = fetch_data()

# Check if the object has get attribute
if (hasattr(data, 'get')):
    print(data.get("Name"))

输出

Audi

总结

AttributeError: 'str' object has no attribute 'get' 发生在你试图调用get()方法时,会发生AttributeError: 'str' object has no attribute 'get' 。如果调用方法返回一个字符串而不是一个字典 对象,也会发生这个错误。

我们可以通过调用 get()方法而不是调用字符串,就可以解决这个错误。我们可以使用 type()方法来检查对象是否为 dictionary 类型,同时,我们可以在执行 get 操作之前,用 hasattr()在执行获取操作之前检查对象是否有有效的获取属性。