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

如何在Python中通过字符串调用类中的方法?

Solutions for Calling Class Methods via Strings

Got it, let's break down how to call class methods using string names in Python—this is a common need in larger projects, so I've got a few reliable approaches for you.

1. Directly Use getattr() with Your Instance

The simplest and most straightforward way is to use Python's built-in getattr() function. This function lets you retrieve an attribute (including methods) from an object using a string name.

Here's how to adapt your example:

class Example:
    def __init__(self, name, address):
        self.name = name
        self.address = address
    def test1(self):
        print(self.name)
    def test2(self):
        print(self.address)

exm = Example("exm", 0x00)
input_user = "test1"

# Get the method from the instance
method = getattr(exm, input_user)
# Call the method
method()

This works because test1 is an attribute of the exm instance—getattr() grabs it by name, and then you can call it like any other method.

2. Handle Nested String References (e.g., "exm.test1")

If your input string includes both the instance name and the method name (like "exm.test1"), you'll need to split the string and resolve each part step by step. Here's how to do that safely:

input_user = "exm.test1"

# Split the string into components
parts = input_user.split('.')
# Start with the first part (the instance name in globals)
current_obj = globals()[parts[0]]
# Iterate through remaining parts to get the method
for part in parts[1:]:
    current_obj = getattr(current_obj, part)
# Call the method
current_obj()

Add Error Handling

It's smart to add error handling to catch cases where the instance or method doesn't exist:

input_user = "exm.test1"
parts = input_user.split('.')

try:
    current_obj = globals()[parts[0]]
    for part in parts[1:]:
        current_obj = getattr(current_obj, part)
    current_obj()
except (KeyError, AttributeError) as e:
    print(f"Error calling method: {e}")

3. Use operator.attrgetter (Alternative Approach)

Another option is to use operator.attrgetter from the standard library. This is useful if you need to reuse the attribute getter multiple times:

from operator import attrgetter

exm = Example("exm", 0x00)
input_user = "test1"

# Create a getter for the method
method_getter = attrgetter(input_user)
# Retrieve and call the method
method_getter(exm)()

For nested references like "exm.test1", you can combine it with globals():

input_user = "exm.test1"
getter = attrgetter(input_user)
getter(globals())()

Important Note: Security

If the input string comes from untrusted sources (like user input), make sure to validate the method name before calling it. For example, you can check if the method is in a list of allowed methods:

allowed_methods = ["test1", "test2"]
input_user = "test1"

if input_user in allowed_methods:
    method = getattr(exm, input_user)
    method()
else:
    print("Method not allowed!")

This prevents malicious users from calling sensitive internal methods (like __del__).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 07:23:16