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

前端 未结 11 460
鱼传尺愫
鱼传尺愫 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:47

    None is used to indicate "not set", whereas any other value is used to indicate a "default" value.

    Hence, if your class copes with empty strings and you like it as a default value, use "". If your class needs to check if the variable was set at all, use None.

    Notice that it doesn't matter if your variable is a string initially. You can change it to any other type/value at any other moment.

提交回复
热议问题