这两个 sn-ps 做不同的事情,所以这不是品味问题,而是在您的上下文中正确的行为问题。 Python documentation 解释了区别,但这里有一些例子:
展品 A
class Foo:
def __init__(self):
self.num = 1
这会将num 绑定到 Foo 实例。对此字段的更改不会传播到其他实例。
因此:
>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1.num = 2
>>> foo2.num
1
展品 B
class Bar:
num = 1
这会将num 绑定到 Bar 类。更改已传播!
>>> bar1 = Bar()
>>> bar2 = Bar()
>>> bar1.num = 2 #this creates an INSTANCE variable that HIDES the propagation
>>> bar2.num
1
>>> Bar.num = 3
>>> bar2.num
3
>>> bar1.num
2
>>> bar1.__class__.num
3
实际答案
如果我不需要类变量,而只需要为我的实例变量设置一个默认值,这两种方法都一样好吗?或者其中一个比另一个更“pythonic”?
展览 B 中的代码显然是错误的:为什么要将类属性(实例创建时的默认值)绑定到单个实例?
展览 A 中的代码没问题。
如果您想在构造函数中为实例变量提供默认值,我会这样做:
class Foo:
def __init__(self, num = None):
self.num = num if num is not None else 1
...甚至:
class Foo:
DEFAULT_NUM = 1
def __init__(self, num = None):
self.num = num if num is not None else DEFAULT_NUM
...甚至:(更可取,但当且仅当您正在处理不可变类型时!)
class Foo:
def __init__(self, num = 1):
self.num = num
这样你就可以做到:
foo1 = Foo(4)
foo2 = Foo() #use default