首页 > 解决方案 > 在用户定义的类中的任意属性上调用方法

问题描述

好的,这可能真的很简单,但我很挣扎。所以,假设我有一个简单的类“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')

如何设置该方法以便可以将其传递给适当的属性?提前感谢您的任何想法!

标签: pythonclassobjectmethods

解决方案


您可以使用 getgetattrsetattr方法。这些允许您通过字符串引用类属性。

您可以将所需的属性传递给该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"`

推荐阅读