繁体   English   中英

在内置命名后命名实例变量是不好的做法

[英]Is it a bad practice to name a instance variable after a built-in

拥有以python内置命名的变量是一种不好的做法,因为它阻止了它们的正确使用 ,并且可能会使读者感到困惑。

但是实例变量怎么样:

class MyClass:
    def __init__(self, type_):
        self.type = type_

对此有一个很好的论据吗?

我会说没关系。

通过Python的标准库,你可以看到很多地方的属性命名与内置命令相同:

例如:

:~/cpython/Lib$ egrep -R "\.set[^a-zA-Z0-9_]" | wc -l
583
:~/cpython/Lib$ egrep -R "\.type[^a-zA-Z0-9_]" | wc -l
319

some_object.type != type(some_object)some_object.type != type(some_object)困惑吗? 是的,至少对我来说。 所以有你自己的好论据反对它: 它可能会使读者感到困惑

很确定有人会发现这个意见 ...

但是 ,这是我的:

不,这不是一个坏习惯。 这些类属性只是实例__dict__区域中的字段(mgnmgnmnnn ... fine,或__slots__ ),因此是实例绑定的。 你不能把self.type与内置type搞错( self.type总是需要用self.访问self. )所以你隐含地限制了范围...有点( 有点 )喜欢什么当你from os import path有一个名为path的变量时...

如果你有:

from os import path
path="/home/borrajax/foo.txt"
path.join(path, ...)  # Eeeeeeermmm... I'm kind of screwed here?

但是,如果你这样做:

import os
path="/home/borrajax/foo.txt"
os.path.join(path, ...)

你完全没问题,因为你的范围很明确。

我看到它的方式(也许有人可能不同意)是类/实例以类似的方式限制范围。 当你看到self.type ,你知道它必须被绑定到一个实例!

但是,你有点...呃......是的...如果你试图覆盖类的内置属性:

class A:
    def __init__(self):
        self.__dict__ = "foo"
        self.a = "hi"

if __name__ == "__main__":
    a = A()

会给你:

$ python ./stack_055_B.py
Traceback (most recent call last):
  File "./stack_055_B.py", line 7, in <module>
    a = A()
  File "./stack_055_B.py", line 3, in __init__
    self.__dict__ = "foo"
TypeError: __dict__ must be set to a dictionary, not a 'str'

暂无
暂无

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

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