如何在Python中正确声明实例字段

时间:2014-08-07 06:49:49

标签: python coding-style

这可能是一个愚蠢/琐碎的问题,但我对此事感到困惑。

在构造函数或类体本身中声明实例字段的鼓励(pythonic)方式是什么?

class Foo:
    """ Foo class """

    # While we are at it, how to properly document the fields?
    bar = None

    def __init__(self, baz):
        """ Make a Foo """

        self.bar = baz

OR:

class Foo:
    """ Foo class """

    def __init__(self, baz):
        """ Make a Foo """

        self.bar = baz

2 个答案:

答案 0 :(得分:3)

这是一个期待的问题。阅读代码的人将期望在类的顶级定义的属性将是类属性。然后,您始终在__init__中替换它们的事实只会造成混淆。

因此,您应该使用选项2,在__init__中定义实例属性。

在记录属性方面,选择一个docstring样式并坚持下去;我喜欢Google's,其他选项包括numpy's

class Foo:
    """A class for foo-ing bazs. 

    Args:
      baz: the baz to foo

    Attributes:
      bar: we keep the baz around 

    """

    def __init__(self, baz):
        self.bar = baz

答案 1 :(得分:2)

为了简单起见,让我们使用类变量bar定义类Foo:

In [34]: class Foo: bar = 1

现在,观察:

In [35]: a = Foo()

In [36]: a.bar
Out[36]: 1

In [37]: Foo.bar = 2

In [38]: a.bar
Out[38]: 2

Foo.bar的更改会影响该类的现有实例。

出于这个原因,人们通常会避免使用类变量,而不是实例变量,除非有人想要这些副作用。

相关问题