解决PyCharm中报出 “Instance attribute xxx defined outside __init__“ 的警告
生活随笔
收集整理的這篇文章主要介紹了
解决PyCharm中报出 “Instance attribute xxx defined outside __init__“ 的警告
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
解決 PyCharm 中報出 "Instance attribute xxx defined outside \_\_init\_\_" 的警告
問題描述:
Pycharm 提示 Instance attribute users_index defined outside __init__ 的警告
示例代碼:
class UserBehavior(TaskSet):def on_start(self):self.users_index = 0 #會出現下劃線提示Instance attribute users_index defined outside __init__self.groups_index = 0 #會出現下劃線提示Instance attribute groups_index defined outside __init__原因分析:
-
實例屬性 attribute_name 定義在 init之外
-
這個提示背后的想法是:為了可讀性,希望通過讀取它的 __ init __ 方法來查找實例可能具有的所有屬性。構造方法里做賦值以外的事情,會降低代碼的可測試性。
-
分割初始化為其他方法。在這種情況下,您可以在 __ init __ 中簡單地將屬性分配給無子初始化方法。
解決方案1:
在 inint 中定義一個名字,賦值為None
修改代碼如下:
class UserBehavior(TaskSet):def __init__(self):self.users_index = Noneself.groups_index = Nonedef on_start(self):self.users_index = 0self.groups_index = 0解決方案2:
在 settings -> editor -> inspections -> python 取消勾選提示
總結
以上是生活随笔為你收集整理的解决PyCharm中报出 “Instance attribute xxx defined outside __init__“ 的警告的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何确保ChatGPT的公平性、透明性和
- 下一篇: 如何构建ChatGPT的生态系统?