如何将str类型转为对象?趣味数据库搜索函数遇AttributeError报错
Hey there! Let's break down your problem and fix that frustrating error step by step.
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.
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!")
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

