getattr
是 Python 的内置函数,用于动态地获取对象的属性或方法
以下是使用 getattr
的一些通用解决方案:
class MyClass:
def __init__(self):
self.attribute1 = "value1"
self.attribute2 = "value2"
def method1(self):
return "method1 called"
def method2(self):
return "method2 called"
instance = MyClass()
# 获取属性值
attribute1 = getattr(instance, "attribute1", "default_value")
print(attribute1) # 输出:value1
# 获取方法并调用
method1 = getattr(instance, "method1", None)
if method1:
result = method1()
print(result) # 输出:method1 called
class MyClass:
def method1(self):
return "method1 called"
def method2(self):
return "method2 called"
def call_method(instance, method_name):
method = getattr(instance, method_name, None)
if method:
return method()
else:
return f"Method '{method_name}' not found."
instance = MyClass()
print(call_method(instance, "method1")) # 输出:method1 called
print(call_method(instance, "method2")) # 输出:method2 called
getattr
:class MyClass:
def __init__(self):
self.attribute1 = "value1"
self.attribute2 = "value2"
def __getattr__(self, name):
if name.startswith("custom_"):
return f"Custom attribute '{name}' accessed."
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'")
instance = MyClass()
print(instance.custom_attribute) # 输出:Custom attribute 'custom_attribute' accessed.
这些示例展示了如何使用 getattr
访问对象的属性和方法。你可以根据具体需求调整这些示例以满足你的需求。
领取专属 10元无门槛券
手把手带您无忧上云