Python中getattr()的作用及如何动态调用不同类的同名函数
First, let's fix the core issue with your current code: the names list contains strings (like "classA"), not the actual class objects. Strings don't have a .function() method, so that's why your code won't work. Let's break this down step by step and explain how getattr() helps.
What is getattr()?
Think of getattr() as a handy tool that lets you "look up" something (a method, variable, etc.) inside an object using a string. For example:
- If you have an instance
my_objwith a methodmy_method(),getattr(my_obj, "my_method")is exactly the same as writingmy_obj.my_method. - It’s perfect for when you only know the name of the thing you want to access as a string (like your list of class names).
Step-by-Step Implementation
Case 1: Your classes use static/class methods
If function() is a static method (it doesn’t need an instance of the class to run), here’s how to make it work:
First, define your classes:
class classA: @staticmethod def function(): return "Result from classA" class classB: @staticmethod def function(): return "Result from classB"
Now modify your loop to get the actual class from the string, then call the function:
names = ["classA", "classB"] for class_name in names: # Get the real class object using the string name current_class = globals()[class_name] # Use getattr() to fetch and call the function result = getattr(current_class, "function")() # Or you could also write: result = current_class.function() print(result)
Case 2: Your classes need an instance to call function()
If function() is an instance method (it requires an object of the class to work), you’ll need to create an instance first:
Define the classes:
class classA: def function(self): return "Result from classA instance" class classB: def function(self): return "Result from classB instance"
Adjust the loop to create an instance before calling the method:
names = ["classA", "classB"] for class_name in names: # Get the class object current_class = globals()[class_name] # Create an instance of the class instance = current_class() # Use getattr() to get and run the method result = getattr(instance, "function")() # Or equivalently: result = instance.function() print(result)
Why use getattr() here?
In your specific example, since you know the method name is exactly "function", you could call it directly (like current_class.function()). But getattr() becomes really useful if the method name is also stored as a string (e.g., method_name = "function"). It makes your code flexible if you ever need to change the method name later without rewriting the loop.
内容的提问来源于stack exchange,提问作者Greg Symsym

