python - 重写实例方法的 getattribute 并使用方法输入变量

标签 python python-3.x python-2.7 oop getattribute

我有课Titles其中包含生成许多不同标题所需的代码。每个标题方法都接受变量 rules以便灵活生成正确的标题。无论我调用哪种方法,我都想应用某些格式化步骤。例如,将所有 float 四舍五入到一位小数。我试图通过__getattribute__来做到这一点,但不知道如何向其提供函数变量(即 rules )。这可能吗?是__getattribute__可以访问输入变量吗?

这是一个简单的示例:

import re
class Titles:
    def __init__(self, name):
        self.name = name
    def __getattribute__(self,attr):
        res = object.__getattribute__(self, attr)() #I need to insert rules here
                                                    #somewhere into the function call
        if isinstance(res, str):
            return re.sub(
                    r'\d+\.\d{1,}', lambda m: format(float(m.group(0)), '.1f')
        return res
    def title(self, rules):
        return '{} has spent {} hours on this project'.format(self.name, rules)    

否则,我想我可以有某种“调用者”方法来调用各种方法,然后在返回之前格式化它们的输出......

最佳答案

这听起来像是一个装饰器解决方案:

import re
class Titles:
    def __init__(self, name):
        self.name = name
    @title_decorator
    def title(self, rules):
        return '{} has spent {} hours on this project'.format(self.name, rules)

    @staticmethod
    @title_decorator
    def title2(rules):
        'Also works for {} staticmethods!'.format(rules)

def title_decorator(func):
    def new_function(*args):
        # do something on rules
        func_result = func(*args)
        # do something on func result
        return func_result
    return new_function

我不确定您是否想要格式化输出或输入,但您可以两者都做。

关于python - 重写实例方法的 getattribute 并使用方法输入变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49921340/

相关文章:

python - 按其中一个键的值拆分字典

python - 我可以加入类(class)列表吗?

python - 生成所有具有字符 a、b 或 c 且长度等于 n 且最多有 1 个 b 和 2 个 c 的字符串

python - python中类型转换函数的时间复杂度是多少?

python - 如何克服 python 中的正则表达式深度限制?

python : Find tuples from a list of tuples having duplicate data in the 0th element(of the tuple)

Python lxml - 返回空列表

Python try/except 不断尝试直到没有错误

python - 为什么我的表格总是未绑定(bind)?

java - 使用 python 脚本转换输入以输入到连接到 Android 应用程序的 firebase 的tensorflow lite ML Kit