类方法和属性的命名约定

7

如何为类属性和方法(函数)命名是最佳实践?

class Base():   
    def __init__(self):
        self.name = 'My Name'
    def print_this(self):
        print "Hello"

创建一个类的实例:
a = Base()

了解此类中可用的方法和属性:

print dir(a)

得到以下输出:

['__doc__', '__init__', '__module__', 'name', 'print_this']

阅读dir()输出中的名称,无法看出变量(类属性)和方法(类函数)的所在位置。

使用什么命名约定来区分变量和函数(或属性和方法)?


9
如果我是你,我会去阅读《PEP 8》以了解命名惯例。PEP 8 - Adam Smith
还要看一下 flake8 https://pypi.python.org/pypi/flake8 并开始使用它。 - gawel
1
查看PEP 8肯定是个好主意,但值得注意的是,在Python中尝试实现这样的命名约定充满了陷阱。例如,一个property应该采用属性变量样式还是实例方法样式?根据上下文,它们同样有效。 - Silas Ray
打印出以下代码:print {name: type(a[name]) for name in dir(a)} - 现在你知道了类型。 - Eric
这个问题没有正确答案。“我应该使用什么命名约定?” <-- 这是基于个人意见的。 “通过名称,我如何确定什么是方法和什么是变量?” <-- 你无法确定。 - Lasse V. Karlsen
@SilasRay 我们已经有了这种情况:函数是小写的,类是驼峰式大小写。两者都可以被调用,并且在某种程度上是可互换的。 - glglgl
1个回答

7

通常应在方法名中使用动词,例如print_thiscalculate_thatsave,因为它们执行某些操作。

而属性和属性将只是一个简单的名词,例如namestatuscount,因为它们只包含一个值或者在属性的情况下,底层函数应计算并返回一个值,没有其他副作用。

不过,您的问题比较模糊:

  • is it about naming conventions in Python? For this you should refer to the famous PEP8 document

  • is it about how to distinguish between methods and attributes by looking at their names? for this see my rule of thumb above

  • is it about how to distinguish between methods and attributes programmatically? In this case you can use the inspect module to provide a definitive answer, for example:

    import inspect
    
    for attr in dir(a):
        if inspect.ismethod(getattr(a, attr)):
            print '%s is a method' % attr
        else:
            print '%s is an attribute or property' % attr
    

1
布尔值的命名有些困难。x.printable 还好,但是 y.calculate_slowly 单从名称上看就不明确是一个方法还是一个属性。 - Eric
callable()技巧并不总是有效。如果属性或者属性包含可调用对象呢? - glglgl
@glglgl 很好的观点...已经更改为使用inspect.ismethod - Anentropic
@Eric - 对于布尔变量,请在变量前加上“is”或“do”前缀。例如,“is_printable”和“do_calculate_slowly”。 - Craig S. Anderson
2
@CraigS.Anderson:我同意使用is_,但作为一个命令动词,do_在我的理解中强烈暗示了“方法”。 - Eric

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接