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

前端 未结 11 458
鱼传尺愫
鱼传尺愫 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: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)
    <type 'NoneType'>
    >>> x = "text"
    >>> print type(x)
    <type 'str'>
    >>> x = 42
    >>> print type(x)
    <type 'int'>
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-30 13:07

    Since both None and "" are false, you can do both. See 6.1. Truth Value Testing.

    Edit

    To answer the question in your edit: No, you can assign a different type.

    >>> a = ""
    >>> type(a)
    <type 'str'>
    >>> a = 1
    >>> type(a)
    <type 'int'>
    
    0 讨论(0)
  • 2021-01-30 13:08

    Either way is okay in python. I would personally prefer "". but again, either way is okay

    >>>x = None
    >>>print(x)
    None
    >>>type(x)
    <class 'NoneType'>
    >>>x = "hello there"
    >>>print(x)
    hello there
    >>>type(x)
    <class 'str'>
    >>> 
    >>>x = ""
    >>>print(x)
    
    >>>type(x)
    <class 'str'>
    >>>x = "hello there"
    >>>type(x)
    <class 'str'>
    >>>print(x)
    hello there
    
    0 讨论(0)
  • 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, ...
    
    0 讨论(0)
提交回复
热议问题