Wat*_*uck 3 python optional-parameters
我经常读到,检查是否定义了变量在某种程度上是一个错误的设计选择。但是我没有其他方法可以处理类方法中的可选参数。因此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)
Run Code Online (Sandbox Code Playgroud)
这将打印以下行:
meow meow
hiss hiss
0 0
Run Code Online (Sandbox Code Playgroud)
self当时尚未定义,因此我不能简单地设置默认值,而不是None:
def make_sound_twice(self, sound=self.default_sound):
Run Code Online (Sandbox Code Playgroud)
您显示的代码绝对没有错。 实际上,这很惯用。
我经常读到,检查是否定义了变量在某种程度上是一个错误的设计选择
在您显示的示例中,变量已定义。设置为None。
进行检查is None完全可以。在某些情况下,下面的技术可以用来替换所有falsy值(None,0,""用默认等):
DEFAULT = ...
def f(arg = None):
arg = arg or DEFAULT
...
Run Code Online (Sandbox Code Playgroud)
但是,这不适用于您的情况,因为您声明需要能够将零传递给函数。