python - 在用户定义的类中的任意属性上调用方法
问题描述
好的,这可能真的很简单,但我很挣扎。所以,假设我有一个简单的类“Simple”,它有一些属性a 和b。我有一个方法,“trim”,可以一次用于一个属性:
class Simple():
def __init__(self, a=None, b=None):
self.a = a
self.b = b
def trim(self.[???]):
...do some stuff...
return self
现在,我希望用户能够将该方法应用于任何属性(即 a 和 b),例如:
simple_with_a_trimmed = simple.trim('a')
或者
simple_with_b_trimmed = simple.trim('b')
如何设置该方法以便可以将其传递给适当的属性?提前感谢您的任何想法!
解决方案
您可以使用 getgetattr
和setattr
方法。这些允许您通过字符串引用类属性。
您可以将所需的属性传递给该trim
方法。然后,您可以使用 检索指定属性的值getattr
。然后,您可以转换它并返回它,或者使用setattr
-- 修改它来更新对象。
下面是一个简单的例子。该trim1
方法仅返回(转换后的)属性的值,但不更新对象。该trim2
方法改变了对象本身——它更新了指定属性的值。
我还添加了一个__str__
方法来显示每次调用后对象如何变化。
class Simple:
def __init__(self, a=None, b=None):
self.a = a
self.b = b
def trim1(self, attr):
# Get value of the attribute
current_value = getattr(self, attr)
# Transform and return the value of the attribute
# Removing whitespace as an example
return current_value.strip()
def trim2(self, attr):
# Get value of the attribute
current_value = getattr(self, attr)
# Transform the value of the attribute
# Removing whitespace as an example
current_value = current_value.strip()
# Update the value of the attribute
setattr(self, attr, current_value)
def __str__(self):
return f'a: "{self.a}", b: "{self.b}"'
# Create an object of type Simple
simple = Simple(' data1', 'data2 ')
# These methods do not change the object, but return the transformed value
a = simple.trim1('a')
b = simple.trim1('b')
print(f'Returned value of a: "{a}"')
print(f'Returned value of b: "{b}"')
print(simple) # Prints `a: " data1", b: "data2 "`
# Apply the transformation to attribute `a`
simple.trim2('a')
print(simple) # Prints `a: "data1", b: "data2 "`
# Apply the transformation to attribute `b`
simple.trim2('b')
print(simple) # Prints `a: "data1", b: "data2"`
推荐阅读
- javascript - Chart.js 使用 select 显示不同的图表
- mysql - 如果行不存在,则 SQL 添加行
- c - 我们什么时候使用ioeventfd又如何?
- javascript - 如何从浏览器运行多个自定义协议
- python - 为什么 onehotencoder 使用附加列转换器将对象数组更改为浮点数组
- c# - 如何发送回wpf中的元素?
- docker - symfony 5.3 日志文件无法以附加模式打开:无法打开流(docker)
- python - 在 mouseup 上触发事件,而不是在面板应用程序中使用参数化类连续触发事件
- c# - 我怎样才能让玩家在向左滑动时彼此靠近,而在向右滑动时他们会移动到两侧?
- javascript - 创建时无法在 vue js 组件中执行 .find() 循环