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

前端 未结 11 463
鱼传尺愫
鱼传尺愫 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条回答
  •  -上瘾入骨i
    2021-01-30 13:00

    If not having a value has a meaning in your program (e.g. an optional value), you should use None. That's its purpose anyway.

    If the value must be provided by the caller of __init__, I would recommend not to initialize it.

    If "" makes sense as a default value, use it.

    In Python the type is deduced from the usage. Hence, you can change the type by just assigning a value of another type.

    >>> x = None
    >>> print type(x)
    
    >>> x = "text"
    >>> print type(x)
    
    >>> x = 42
    >>> print type(x)
    
    

提交回复
热议问题