【发布时间】:2019-07-20 12:45:46
【问题描述】:
我经常读到检查变量是否已定义在某种程度上是一个糟糕的设计选择。但我看不出有其他方法可以处理类方法中的可选参数。那么下面代码对make_sound_twice的可选参数的处理方式有问题吗?
class Cat(object):
def __init__(self):
self.default_sound = 'meow'
def make_sound_twice(self, sound=None):
if sound is None:
sound = self.default_sound
print("{sound} {sound}".format(sound=sound))
kitty = Cat()
kitty.make_sound_twice()
custom_sound = 'hiss'
kitty.make_sound_twice(custom_sound)
custom_sound = 0
kitty.make_sound_twice(custom_sound)
这将打印以下行:
meow meow
hiss hiss
0 0
self 那时没有定义,所以我不能简单地设置一个默认值来代替None:
def make_sound_twice(self, sound=self.default_sound):
【问题讨论】:
-
您的代码不是检查变量是否已定义,而是检查其值。
标签: python optional-parameters