You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类方法中用f-string重构代码时,如何正确输出对应变量信息?

重构重复代码:解决打印错误与属性赋值问题

问题根源

你之前的写法里,把属性的值(比如self.a的内容)传给log_and_set,函数内的a只是局部变量,f-string的{a=}只会显示这个局部变量的名字和值,无法关联到类的属性名(比如a或b)。要实现目标打印效果,必须传递属性名的字符串,而非属性值。同时,直接给局部变量赋值无法修改类实例的属性,得用setattr来处理。

重构后的完整代码

from dataclasses import dataclass

@dataclass
class Example2:
    a: str
    b: str
    c: str
    
    def repeated_code(self):
        # 用字典映射c值与对应属性名,新增场景只需加键值对
        c_to_attr = {
            'A': 'a',
            'B': 'b'
            # 比如新增'C': 'c', 'D': 'd'...
        }
        target_attr = c_to_attr.get(self.c)
        if not target_attr:
            return
        
        current_val = getattr(self, target_attr)
        if current_val != "":
            self.log_and_set(target_attr, "")

    def log_and_set(self, attr_name, new_val):
        current_val = getattr(self, attr_name)
        # 完全匹配你要的打印格式
        print(f"as {self.c = } and {attr_name} = '{current_val}', set {attr_name} to ''")
        # 正确修改类实例的属性
        setattr(self, attr_name, new_val)

关键说明

  1. 打印问题解决:
    通过传递属性名字符串(如"a"),用getattr获取当前值,在f-string中直接使用attr_name就能显示对应的属性名,搭配当前值实现你需要的输出格式。如果偏好{变量名=}的语法,也可以改成:

    print(f"as {self.c = } and {attr_name = } and {current_val = }, set {attr_name} to ''")
    

    输出会更贴近你最初的写法:as self.c = 'A' and attr_name = 'a' and current_val = 'test', set a to ''

  2. 属性赋值问题解决:
    使用setattr(self, attr_name, new_val)直接修改类实例的属性,替代局部变量赋值,这样就能正确更新self.a或self.b的值。

  3. 扩展性优化:
    用字典c_to_attr映射c的值与对应属性名,新增场景时只需在字典中添加键值对,无需编写大量if判断,更适合超过10个场景的情况。

内容的提问来源于stack exchange,提问作者David Masip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 14:05:38