像staticmethod一样定义自定义decorator

2024-10-04 13:19:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用factory-boy包和pylint进行静态linting。对于以下代码,linter发出no-self-argument错误。你知道吗

import factory
from factory import Factory, Faker

class MyTestFactory(Factory):
    class Meta:
        model = dict

    a = Faker("pyint")
    b = Faker("pyint")

    @factory.lazy_attribute
    def a_and_b(obj):  # <-- no-self-argument here
        return obj.a + obj.b

if __name__ == "__main__":
    O1 = MyTestFactory.build()
    print(f"dbg: {O1=}")

example2.py:12:4: E0213: Method should have "self" as first argument (no-self-argument)

我不想把信息完全隐藏起来。但是,我想告诉pylint,@factory.lazy_attribute装饰器的行为就像@staticmethod内置的一样,因此该方法只需要少一个参数。有可能吗?pylintrc中是否有负责静态方法声明的特殊设置?你知道吗


Tags: noimportselfobjfactoryattributeargumentlazy
1条回答
网友
1楼 · 发布于 2024-10-04 13:19:14

根据doc

This decorates an instance method that should take a single argument, self; the name of the method will be used as the name of the attribute to fill with the return value of the method:

这意味着您应该将参数命名为self,而不是obj

相关问题 更多 >