简体   繁体   English

class 'Runattr' 的未解析属性参考 'cfg'

[英]Unresolved attribute reference 'cfg' for class 'Runattr'

I have declared a class as follows:我已经声明了一个 class 如下:

class Runattr:
    pass

run = Runattr()
run.cfg = 'some str'

When I am trying to access run.cfg further in my code, PyCharm gives me the following warning and I am not able to autocomplete run.cfg:当我尝试在我的代码中进一步访问 run.cfg 时,PyCharm 给了我以下警告,我无法自动完成 run.cfg:

Unresolved attribute reference 'cfg' for class 'Runattr' Inspection info: This inspection detects names that should resolve but don't. class 'Runattr' 的未解析属性引用 'cfg' 检查信息:此检查检测应解析但未解析的名称。 Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases.由于动态调度和鸭子类型,这在有限但有用的情况下是可能的。 Top-level and class-level items are supported better than instance items.顶级和类级别的项目比实例项目更受支持。

I am new to using classes.我是使用类的新手。 Can someone tell me why I am seeing this warning and can this be modified to get rid of the warning?有人可以告诉我为什么我会看到这个警告,并且可以修改它以消除警告吗?

you have to declare on a field named cfg您必须在名为 cfg 的字段上声明

class Runattr:
    cfg = ''

run = Runattr()
run.cfg = 'some str'

It's just a PyCharm warning (not an error,), since it can't figure out whether that class really should have a cfg attribute.这只是一个 PyCharm警告(不是错误),因为它无法确定 class 是否真的应该具有cfg属性。

Assuming you're using a modern Python version, add an annotation for such a field:假设您使用的是现代 Python 版本,请为此类字段添加注释:

class Runattr:
    cfg: str  # denotes there would/could be a string `cfg`

run = Runattr()
run.cfg = 'some str'

Classes and instances can nevertheless have any attributes (and heck, you can even do setattr(run, "oh this is fun", True) to have an attribute that's not a valid Python identifier), it's just that IDEs can't be infinitely smart about the dynamic nature here.类和实例仍然可以有任何属性(见鬼,你甚至可以执行setattr(run, "oh this is fun", True)来拥有一个不是有效的 Python 标识符的属性),只是 IDE 不能无限聪明地了解这里的动态性质。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM