【问题标题】:Proper python naming convention for class attributes/properties that "are" classes?“是”类的类属性/属性的正确python命名约定?
【发布时间】:2013-09-19 23:01:50
【问题描述】:

好的,在下面的代码中,属性名称应该是什么?

class ClassOne(object):
    a = 1

class ClassTwo(object):
    some_class = ClassOne

    def _get_other_class(self):
        return self._other_class

    def _set_other_class(self, value):
        self._other_class = value

    other_class = property(_get_other_class, _set_other_class)

    class InnerClass(object):
        b = 2

“some_class”是“some_class”因为它是一个属性还是“SomeClass”因为它引用了一个类更合适?与“other_class”相同。所以第二个选项更像是:

class ClassOne(object):
    a = 1

class ClassTwo(object):
    SomeClass = ClassOne

    def _get_other_class(self):
        return self._other_class

    def _set_other_class(self, value):
        self._other_class = value

    OtherClass = property(_get_other_class, _set_other_class)

    class InnerClass(object):
        b = 2

如果大写它们似乎更清楚它们是类,但是 pep8 说属性应该是带有下划线的小写。然而,InnerClass 最终成为 ClassTwo 的一个属性,名称大写。

【问题讨论】:

  • 内部类、getter、setter ... 你的最后一种语言不会是 Java,对吧? PEP 8 没有解决您的情况,因为它很少出现。你的用例是什么?
  • @StevenRumbalski:实际上,我认为 PEP 8 确实很好地涵盖了这种情况。但是您的更大观点是有效的。很难回答关于语义上空且完全不是 Pythonic 风格的代码的风格问题……

标签: python class properties attributes naming-conventions


【解决方案1】:

在您的示例中,这些变量保存类对象的事实似乎无关紧要。

看看 PEP 8 关于类方法的参数的说法:

始终使用cls 或类方法的第一个参数。

在下一行,你有这个例子:

如果函数参数的名称与保留关键字发生冲突,通常最好在结尾附加一个下划线,而不是使用缩写或拼写错误。因此class_ 优于clss

您可以在整个标准库中找到这两种情况和类似情况的示例(例如,分配 eggs = type(spam))。

变量(属性、参数、局部变量、全局变量等——是的,还有属性,因为重点是它们看起来像普通的实例属性)使用小写的名称。你期望它们持有什么类型的价值并不重要。


但是,InnerClass 最终成为具有大写名称的 ClassTwo 的属性。

这是真的,但它不相关。这与ClassTwo 最终成为模块中的全局变量的方式完全相同。 InnerClass 被定义为一个类,而不是一个变量/参数/属性。


当然,您可以提出不太清楚的边缘情况。例如,您应该使用foo_bar = types.ClassType('foo_bar', (object,), {}) 还是FooBar = types.ClassType('FooBar', (object,), {})foo_bar = types.ClassType('FooBar', (object,), {})

但 PEP 8 并不是一套涵盖所有场景的硬性规则;总是有边缘情况。大多数时候,类和变量之间的区别是显而易见的,因此 PEP 8 的推荐是显而易见的。当区别不明显时,PEP 8 也无济于事。

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 2017-03-28
    • 2010-09-20
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    相关资源
    最近更新 更多