You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将str类型转为对象?趣味数据库搜索函数遇AttributeError报错

Hey there! Let's break down your problem and fix that frustrating error step by step.

What's Causing the AttributeError?

The error 'str' object has no attribute 'print_info' happens because when you run person = input("Who are you searching for? "), the person variable stores a plain string (like "Alice" or "Bob"), not an instance of your custom person class. Strings don't have a print_info() method—that's a method you’ve defined on your object, right? So when you try to call person.print_info() later in your code, Python throws an error because it can’t find that method on a basic string.

How to Convert the String to a Recognizable Object

The solution is to map the input string (the person’s name) to the actual object in your database. Here’s how to do it:

1. Store Your Objects in a Dictionary First

First, organize all your person objects in a dictionary where the keys are name strings (matching what users will input) and the values are the actual objects. For example:

# Assuming this is your custom Person class
class Person:
    def __init__(self, name, job, age):
        self.name = name
        self.job = job
        self.age = age
    
    def print_info(self, info_type):
        # Your logic to print specific details
        if info_type == "Job":
            print(f"{self.name}'s job is {self.job}")
        elif info_type == "Age":
            print(f"{self.name} is {self.age} years old")
        # Add other info types as needed

# Create a dictionary to map names to Person objects
people_database = {
    "Alice": Person("Alice", "Software Engineer", 32),
    "Bob": Person("Bob", "Graphic Designer", 27),
    "Charlie": Person("Charlie", "Data Analyst", 29)
}

2. Adjust Your Search Code to Use the Dictionary

Now modify your existing code to pull the object from the dictionary using the input string:

if password == "xxxx":
    search_name = input("Who are you searching for? ")
    if search_name == "Everyone":
        print("Searching for everyone...")
        info = input("What do you want to know about everyone? ")
        # Loop through all Person objects in the dictionary
        for person in people_database.values():
            person.print_info(info)
    else:
        # Check if the name exists in our database
        if search_name in people_database:
            target_person = people_database[search_name]
            info = input("What do you want to know about them? ")
            target_person.print_info(info)
        else:
            print(f"Oops, {search_name} isn't in the database yet!")
Why This Works

By using the dictionary, you’re essentially translating the user’s input string into the actual object you created. Now when you call target_person.print_info(), you’re calling the method on a real Person object—not a string—so Python won’t throw that AttributeError anymore.

内容的提问来源于stack exchange,提问作者SnitchingAuggie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:02:06