Initialize a string variable in Python: “” or None?

前端 未结 11 456
鱼传尺愫
鱼传尺愫 2021-01-30 12:44

Suppose I have a class with a string instance attribute. Should I initialize this attribute with \"\" value or None? Is either

11条回答
  •  北海茫月
    2021-01-30 13:13

    For lists or dicts, the answer is more clear, according to http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#default-parameter-values use None as default parameter.

    But also for strings, a (empty) string object is instanciated at runtime for the keyword parameter.

    The cleanest way is probably:

    def myfunc(self, my_string=None):
        self.my_string = my_string or "" # or a if-else-branch, ...
    

提交回复
热议问题