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

时间:2019-07-20 12:45:46

标签: 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)

这将打印以下行:

meow meow
hiss hiss
0 0

self当时尚未定义,所以我不能简单地设置默认值而不是None

def make_sound_twice(self, sound=self.default_sound):

2 个答案:

答案 0 :(得分:7)

您显示的代码绝对没有错。实际上,这很惯用。

  

我经常读到,检查是否定义了变量在某种程度上是错误的设计选择

在您显示的示例中,定义了变量 。它只是设置为exampleDF$zacko[ is.na(exampleDF$zacko) ] <- "REPLACEMENT"

使用None进行检查完全可以。在某些情况下,可以使用以下技术用默认值替换所有伪造的值(is NoneNone0等)

""

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

答案 1 :(得分:1)

您可以使其更加清洁:

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。

相关问题