[英]Pycharm visual warning about unresolved attribute reference
I have two classes that look like this:我有两个看起来像这样的类:
class BaseClass(object):
def the_dct(self):
return self.THE_DCT
class Kid(BaseClass):
THE_DCT = {'vars': 'values'}
# Code i ll be running
inst = Kid()
print(inst.the_dct)
Inheritance has to be this way;继承必须是这样; second class containing
THE_DCT
and first class containing def the_dct
.第二类包含
THE_DCT
和第一类包含def the_dct
。
It works just fine, but my problem is that i get a warning in Pycharm (unresolved attribute reference), about THE_DCT
in BaseClass
.它工作得很好,但我的问题是我在 Pycharm(未解析的属性引用)中
THE_DCT
关于BaseClass
中的 THE_DCT 的警告。
Within BaseClass
you reference self.THE_DCT
, yet when PyCharm looks at this class, it sees that THE_DCT
doesn't exist. 在
BaseClass
你引用self.THE_DCT
,但是当PyCharm查看这个类时,它会看到THE_DCT
不存在。
Assuming you are treating this as an Abstract Class, PyCharm doesn't know that that is your intention. 假设您将此视为抽象类,PyCharm不知道这是您的意图。 All it sees is a class accessing an attribute, which doesn't exist, and therefore it displays the warning.
它看到的只是一个访问属性的类,它不存在,因此它显示警告。
Although your code will run perfectly fine (as long as you never instantiate BaseClass
), you should really change it to: 虽然你的代码运行得很好(只要你永远不会实例化
BaseClass
),你应该把它改为:
class BaseClass(object):
THE_DCT = {}
def the_dct(self):
return self.THE_DCT
In addition to the existing answers, or as an alternative, you can use Type Hints
.除了现有的答案,或者作为替代,您可以使用
Type Hints
。 This satisfies PyCharm's warnings and also distinguishes the attribute as being inherited (or at least not native to the class).这满足 PyCharm 的警告,并且还将该属性区分为继承的(或至少不是该类的本机)。 It's as simple as adding
THE_DCT: dict
at the very top of your class (before anything else).就像在班级的最顶部(在其他任何事情之前)添加
THE_DCT: dict
一样简单。
class BaseClass(object):
THE_DCT: dict # Add a type-hint at the top of the class, before anything else
def the_dct(self):
return self.THE_DCT
class Kid(BaseClass):
THE_DCT = {'vars': 'values'}
I prefer this approach because it negates the need to unnecessarily add a placeholder attribute ( self.THE_DCT = {}
) and, because it's visually different than declaring an attribute, it can also negate the need for adding a comment next to the placeholder attribute to explain that it's inherited.我更喜欢这种方法,因为它不需要不必要地添加占位符属性(
self.THE_DCT = {}
),并且因为它在视觉上与声明属性不同,它还可以否定在占位符属性旁边添加注释的需要解释它是继承的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.