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

Python中getattr()的作用及如何动态调用不同类的同名函数

Solution to Calling Same-Named Functions from Different Classes

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_obj with a method my_method(), getattr(my_obj, "my_method") is exactly the same as writing my_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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:24:34