Is it bad practice to use a built-in function name as an attribute or method identifier?

早过忘川 提交于 2019-11-26 13:48:29

问题


I know to never use built-in function names as variable identifiers.

But are there any reasons not to use them as attribute or method identifiers?

For example, is it safe to write my_object.id = 5, or define an instance method dict in my own class?


回答1:


It won't confuse the interpreter but it may confuse people reading your code. Unnecessary use of builtin names for attributes and methods should be avoided.

Another ill-effect is that shadowing builtins confuses syntax highlighters in most python-aware editors (vi, emacs, pydev, idle, etc.) Also, some of the lint tools will warn about this practice.




回答2:


Yes it's bad practice. It might not immediately break anything for you, but it still hurts readability of the code.

To selectively quote from PEP20:

Beautiful is better than ugly.
Simple is better than complex.
Readability counts.
If the implementation is hard to explain, it's a bad idea.

Seeing a call to myobject.dict() it would be natural to assume that it's going to return myobject.__dict__, or that myobject.id() returns the same thing as id(myobject)

It's possible for them to find out that they're wrong; but that will take time and effort and probably lead to some mistakes while they figure it out. Calling your attribute myobject.object_id_number is much longer, but makes it clearer that it's different to id(myobject)




回答3:


No, that's fine. Since an object reference is required there is no way to have them shadow the built-in.



来源:https://stackoverflow.com/questions/9109333/is-it-bad-practice-to-use-a-built-in-function-name-as-an-attribute-or-method-ide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!