PyCharm 为 class 中不存在的成员发送警告

PyCharm send warning for no member existing in class

PyCharm Python Lint 不会对不正确的 class 成员发出警告。它继续 运行 我的代码,我下面有 productName 成员,而不是 productNameTest

PyCharm Settings > Misspelling Warnings 在桌面上启用,但是如果成员“拼写正确”但在 class 中不存在,没有发出警告。

我们如何设置 PyCharm 发送没有成员的警告?

产品型号:

@dataclass(init=False)
class ProductModel:
    
    productId: int
    productName: str

class ProductService:

    def __init__(self, productModel: ProductModel):
        self.productModel= productModel

    def getProductModel(self, curveData):
        self.productModel.productNameTest = "ABCD"  # productNameTest is not a member and should give warning

if member "is spelled correctly" but doesn't exist in class, no warning is issued.

这不是 Python class 实例的工作方式。您正在做的是一个属性赋值,它有效地将属性 productNameTest 添加到 ProductService 实例中的 ProductModel 实例。 Python 允许这样的属性 - 如下所述 - 因为它是动态的并且数据 class 定义不禁止在实例上动态设置属性。

3. Data model

Class instances

Attribute assignments and deletions update the instance’s dictionary, never a class’s dictionary. (...)

Special attributes: __dict__ is the attribute dictionary; __class__ is the instance’s class.

如果您在赋值前后检查 __dict__,您可以看到属性已添加且有效 Python。

>>> the_instance = ProductService(ProductModel(1, "two"))
>>> the_instance.productModel.__dict__

{'productId': 1, 'productName': 'two'}

>>> the_instance.get_product_model("curve_data_str")
>>> the_instance.productModel.__dict__

 {'productId': 1, 'productName': 'two', 'productNameTest': 'ABCD'}

How can we setup PyCharm to send a warning for no member?

这里没有任何 PyCharm linter 可以警告你的东西,如果你尝试第 3 方 linter 也不会有警告,了解这一点是程序员的工作。如果您继续阅读上面的文档摘录,解决方案就会变得显而易见:您可以做的是实施 运行 时间异常(这不是 linter 警告):

If the class has a __setattr__() or __delattr__() method, this is called instead of updating the instance dictionary directly.

注意。我将 @dataclass(init=False) 更改为 @dataclass(init=True) 只是为了方便在一行中提供 __init__,它不会改变这个问题所涉及的属性分配的任何内容。