Python Mixin-未解析的属性参考[PyCharm] [英] Python Mixin - Unresolved Attribute Reference [PyCharm]

查看:126
本文介绍了Python Mixin-未解析的属性参考[PyCharm]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用mixin将一系列功能分离到不同的类中.该Mixin仅应与唯一的子类混合:

I am using a mixin to separate a range of functionality to a different class. This Mixin is only supposed to be mixable with the only child class:

class Mixin:
    def complex_operation(self):
        return self.foo.capitalize()

class A(Mixin):
    def __init__(self):
        self.foo = 'foo'

在我的方法Mixin.complex_operation中的

PyCharm给出警告未解析的属性引用foo".

in my method Mixin.complex_operation PyCharm gives warning 'Unresolved Attribute Reference foo'.

我正确使用mixin模式吗? 有没有更好的方法?(我想在我的mixin中有类型提示和自动完成功能,并且我想有多个mixin.)

Am I using the mixin pattern correctly? Is there a better way? (I would like to have type hints and autocompletion in my mixins, and I would like to have multiple mixins.)

推荐答案

在Mixin中声明必要的字段,例如:

Declare the necessary fields in the Mixin like:

class Mixin:
    foo:str

    def complex_operation(self):
        return self.foo.capitalize() 

这样,mixin实际上声明了一个类必须能够使用此mixin的字段.如果扩展类会将不兼容的类型放入声明的字段,则类型提示将创建警告.

This way the mixin actually declares the fields a class must have to be able to use this mixin. Type hint will create warnings if extending class will put incompatible type into declared field.

edit:按照@valex的建议,用foo:str替换foo = None

edit: Replaced foo = None with foo:str as suggested by @valex

这篇关于Python Mixin-未解析的属性参考[PyCharm]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆