简体   繁体   English

在用户定义的 class 中的任意属性上调用方法

[英]call method on an arbitrary attribute in user-defined class

Ok, this is probably really simple but I'm struggling.好的,这可能真的很简单,但我很挣扎。 So, let's say I have a simple class "Simple" that has some attributes a and b.所以,假设我有一个简单的 class “简单”,它具有一些属性 a 和 b。 And I have a method, "trim" that can be used on one attribute at a time:我有一个方法,“trim”,可以一次用于一个属性:

class Simple():

    def __init__(self, a=None, b=None):

        self.a = a
        self.b = b

    def trim(self.[???]):
        ...do some stuff...
        return self

Now, I want the user to be able to apply the method to any of the attributes (ie, a and b) with something like:现在,我希望用户能够将该方法应用于任何属性(即 a 和 b),例如:

simple_with_a_trimmed = simple.trim('a')

or或者

simple_with_b_trimmed = simple.trim('b')

How can I set up the method so that I can pass it the appropriate attribute?如何设置该方法以便可以将其传递给适当的属性? Thanks in advance for any thoughts!提前感谢您的任何想法!

You can use the get getattr and setattr methods.您可以使用 get getattrsetattr方法。 These allow you to refer to a class attribute by a string.这些允许您通过字符串引用 class 属性。

You can pass the desired attribute to the trim method.您可以将所需的属性传递给trim方法。 You can then retrieve the value of the specified attribute using getattr .然后,您可以使用getattr检索指定属性的值。 Then, you can either transform it, and return it, or perhaps modify it using setattr -- to update the object.然后,您可以转换它并返回它,或者使用setattr修改它——以更新object。

Below is a simple example of this in action.下面是一个简单的例子。 The trim1 method merely returns the value of the (transformed) attribute but does not update the object. trim1方法仅返回(转换后的)属性的值,但不会更新 object。 The trim2 method changes the object itself -- it updates the value of the specified attribute. trim2方法改变了 object 本身——它更新了指定属性的值。

I've also added a __str__ method to show how the object changes after each call.我还添加了一个__str__方法来显示 object 在每次调用后如何变化。

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"`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM