python初始化空字符串_在Python中初始化一個字符串變量:“”或None?

本文讨论了在Python类中初始化字符串实例属性的方法,对比了使用空字符串和None的不同场景,并解释了如何选择最适合的初始化方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Suppose I have a class with a string instance attribute. Should I initialize this attribute with "" value or None? Is either okay?

假設我有一個帶有字符串實例屬性的類。我應該使用“”值還是“無”初始化此屬性?好嗎?

def __init__(self, mystr="")

self.mystr = mystr

or

要么

def __init__(self, mystr=None)

self.mystr = mystr

Edit: What I thought is that if I use "" as an initial value, I "declare" a variable to be of string type. And then I won't be able to assign any other type to it later. Am I right?

編輯:我認為如果我使用“”作為初始值,我“聲明”變量是字符串類型。然后我將無法再為其分配任何其他類型。我對嗎?

Edit: I think it's important to note here, that my suggestion was WRONG. And there is no problem to assign another type to a variable. I liked a comment of S.Lott: "Since nothing in Python is "declared", you're not thinking about this the right way."

編輯:我認為這里需要注意的是,我的建議是錯誤的。將另一種類型分配給變量沒有問題。我喜歡S.Lott的評論:“因為Python中沒有任何內容被宣布為”,所以你並沒有以正確的方式思考這個問題。“

8 个解决方案

#1

56

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.

如果沒有值在程序中有意義(例如可選值),則應使用None。無論如何,這都是它的目的。

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

如果該值必須由__init__的調用者提供,我建議不要初始化它。

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.

在Python中,類型是從用法中推導出來的。因此,您可以通過僅指定其他類型的值來更改類型。

>>> x = None

>>> print type(x)

>>> x = "text"

>>> print type(x)

>>> x = 42

>>> print type(x)

#2

11

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

None用於表示“未設置”,而任何其他值用於表示“默認”值。

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.

因此,如果您的類處理空字符串並且您希望它作為默認值,請使用“”。如果您的類需要檢查變量是否已設置,請使用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.

請注意,如果您的變量最初是一個字符串並不重要。您可以在任何其他時刻將其更改為任何其他類型/值。

#3

6

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

初始化空字符串的另一種方法是使用不帶參數的內置str()函數。

str(object='')

STR(對象= '')

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 ''.

請注意str()本身設置默認參數值''的方式。

#4

4

It depends. If you want to distinguish between no parameter passed in at all, and an empty string passed in, you could use None.

這取決於。如果要區分根本沒有傳入的參數和傳入的空字符串,可以使用None。

#5

4

Either might be fine, but I don't think there is a definite answer.

要么可能沒事,但我認為沒有明確的答案。

If you want to indicate that the value has not been set, comparing with None is better than comparing with "", since "" might be a valid value,

如果要表明尚未設置該值,則與None比較比使用“”更好,因為“”可能是有效值,

If you just want a default value, "" is probably better, because its actually a string, and you can call string methods on it. If you went with None, these would lead to exceptions.

如果你只想要一個默認值,“”可能更好,因為它實際上是一個字符串,你可以在其上調用字符串方法。如果你使用None,這些將導致異常。

If you wish to indicate to future maintainers that a string is required here, "" can help with that.

如果您希望向未來的維護者表明此處需要字符串,“”可以幫助解決這個問題。

Complete side note:

If you have a loop, say:

如果你有一個循環,說:

def myfunc (self, mystr = ""):

for other in self.strs:

mystr = self.otherfunc (mystr, other)

then a potential future optimizer would know that str is always a string. If you used None, then it might not be a string until the first iteration, which would require loop unrolling to get the same effects. While this isn't a hypothetical (it comes up a lot in my PHP compiler) you should certainly never write your code to take this into account. I just thought it might be interesting :)

然后潛在的未來優化器會知道str始終是一個字符串。如果你使用None,那么在第一次迭代之前它可能不是一個字符串,這需要循環展開以獲得相同的效果。雖然這不是一個假設(它在我的PHP編譯器中出現了很多),但你絕對不應該編寫代碼來考慮這一點。我只是覺得它可能很有趣:)

#6

2

Either is fine, though None is more common as a convention - None indicates that no value was passed for the optional parameter.

兩者都可以,但是None作為約定更常見 - None表示沒有為可選參數傳遞值。

There will be times when "" is the correct default value to use - in my experience, those times occur less often.

有時候“”是正確的默認值 - 根據我的經驗,這些時間不常發生。

#7

1

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

由於None和“”都是假的,你可以做到這兩點。見6.1。真值測試。

Edit

編輯

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

要回答編輯中的問題:不,您可以指定其他類型。

>>> a = ""

>>> type(a)

>>> a = 1

>>> type(a)

#8

1

對於列表或單詞,答案更清楚,根據http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#default-parameter-values使用None作為默認參數。

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, ...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值