相关疑难解决方法(0)

"=="和"是"之间有区别吗?

我的Google-fu让我失望了.

在Python中,以下两个相等的测试是否等效?

n = 5
# Test one.
if n == 5:
    print 'Yay!'

# Test two.
if n is 5:
    print 'Yay!'
Run Code Online (Sandbox Code Playgroud)

对于您要比较实例的对象(list比如说),这是否适用?

好的,所以这样的答案我的问题:

L = []
L.append(1)
if L == [1]:
    print 'Yay!'
# Holds true, but...

if L is [1]:
    print 'Yay!'
# Doesn't.
Run Code Online (Sandbox Code Playgroud)

所以==测试值测试的地方is是否是同一个对象?

python equality reference semantics

630
推荐指数
11
解决办法
33万
查看次数

比较字符串和空格时,'is'运算符的行为不同

我开始学习Python(python 3.3),我正在尝试is运算符.我试过这个:

>>> b = 'is it the space?'
>>> a = 'is it the space?'
>>> a is b
False
>>> c = 'isitthespace'
>>> d = 'isitthespace'
>>> c is d
True
>>> e = 'isitthespace?'
>>> f = 'isitthespace?'
>>> e is f
False
Run Code Online (Sandbox Code Playgroud)

似乎空间和问号使is行为表现不同.这是怎么回事?

编辑:我知道我应该使用==,我只是想知道为什么is会这样.

python operators object-identity python-3.x

29
推荐指数
3
解决办法
1908
查看次数

Python实习生字符串吗?

在Java中,显式声明的字符串由JVM实现,因此相同String的后续声明会产生两个指向同一String实例的指针,而不是两个单独的(但相同的)字符串.

例如:

public String baz() {
    String a = "astring";
    return a;
}

public String bar() {
    String b = "astring"
    return b;
}

public void main() {
    String a = baz()
    String b = bar()
    assert(a == b) // passes
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,CPython(或任何其他Python运行时)对字符串做同样的事情吗?例如,如果我有一些课程:

class example():
    def __init__():
        self._inst = 'instance' 
Run Code Online (Sandbox Code Playgroud)

并创建此类的10个实例,它们中的每一个都有一个实例变量引用内存中的相同字符串,或者我最终会得到10个单独的字符串?

python memoization string-interning

12
推荐指数
1
解决办法
4912
查看次数