且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我的班级装饰器是否不够Pythonic或PyCharm在棉绒警告中不够聪明?

更新时间:2023-02-05 22:50:14

您的代码在技术上是正确的(因为它可以按预期工作),但请注意,dec将成为TestClass的方法,并且会破坏如果这样调用.为避免这种情况,您至少应将其设为staticmethod.

Your code is technically correct (in that it will work as expected), with the caveat that dec will become a method of TestClass and will break if invoked as such. You should at least make it a staticmethod to avoid this.

wrt/pythonicity,在不需要此装饰器时,将其作为类的一部分确实是不Python的.它仅适用于此类的事实并不是使其成为该类成员的原因,更不用说使其成为公共API的一部分了.

wrt/ pythonicity, it IS indeed unpythonic to make this decorator part of the class when it's not needed. The fact it only applies to this class is not a reason to make it a member of the class, and even less to make it part of the public API.

您可能可以在注释中添加linter提示以使其静音,但是我个人只是从类中提取此装饰器,将其设置为私有,并记录它仅应与该类一起使用.

You can probably add linter hints in comments to silence it, but I'd personnally just extract this decorator from the class, make it private, and document that it's only supposed to be used with this class.

作为旁注:我假设您的empty_func是错误报告和清理工作"的占位符-否则,它只是无用的-但是确实需要在装饰器中对其进行定义吗?

As as side note: I assume your empty_func is a placeholder for the "error reporting and clean-up work" - else it's just plain useless -, but does it really need to be defined in the decorator?