正在检查是否在 Python 中定义了要避免的变量?

Is checking if a variable is defined to be avoided in Python?

我经常读到,检查变量是否已定义在某种程度上是一个糟糕的设计选择。但我看不到其他方法可以处理 class 方法中的可选参数。那么下面代码中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):

您显示的代码绝对没有问题。事实上,它非常地道。

I often read that checking if a variable is defined is somehow a bad design choice

在您显示的示例中,定义了变量 。它只是设置为 None.

is None检查完全没问题。在某些情况下,可以使用以下技术将所有虚假值(None0"" 等)替换为默认值:

DEFAULT = ...

def f(arg = None):
   arg = arg or DEFAULT
   ...

但是,这不适用于您的情况,因为您声明需要能够将零传递给您的函数。

你可以让它稍微干净一点:

def make_sound_twice(self, sound=None):
    sound = self.default_sound if sound is None else sound
    print("{sound} {sound}".format(sound=sound))

或者:

def make_sound_twice(self, sound=None):
    sound = sound if sound is not None else self.default_sound
    print("{sound} {sound}".format(sound=sound))

但是你现在正在做的事情也是惯用的 Python。