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

前端 未结 11 462
鱼传尺愫
鱼传尺愫 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 12:59

    Another way to initialize an empty string is by using the built-in str() function with no arguments.

    str(object='')

    Return a string containing a nicely printable representation of an object.

    ...

    If no argument is given, returns the empty string, ''.

    In the original example, that would look like this:

    def __init__(self, mystr=str())
       self.mystr = mystr
    

    Personally, I believe that this better conveys your intentions.

    Notice by the way that str() itself sets a default parameter value of ''.

提交回复
热议问题