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

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

    Python philosophy is to be readable.
    That's why it's good practice to define your attributes in __init__() even if it's optional.
    In the same spirit, you have to ask yourself what clearer for anyone who reads your code. In fact the type itself give much information about future use of your variable. So:

    kind = None
    

    Is syntaxically correct, but reader does not know much. Is it a string, a code as integer, a list, etc. ?

    kind_str = None
    kind = ""
    

    Both say a little more, the first has the type in its name and the second in its declaration. I would go for the second, neater.

提交回复
热议问题