这些不是无测试.
if val != None:
if not (val is None):
if val is not None:
Run Code Online (Sandbox Code Playgroud)
哪个更好,为什么?
包括我在内的人都知道Python中有一些东西叫它__future__,它出现在我读过的很多模块中.像我这样沉闷的人不知道它为什么存在,以及如何/何时使用它,即使在阅读了Python的__future__文档之后.
那么用示例来解释一下吗?
在基本用法方面,我快速得到了一些答案,看起来都是正确的.
但是,为了进一步了解如何__future__工作:
当我试图理解它时,我刚刚意识到一个让我感到困惑的关键事情,那就是当前的python版本如何包含将在未来版本中发布的内容?如何在当前的python版本中成功编译未来python版本中使用新功能的程序?
所以,我想现在,当前版本已经打包了一些潜在的功能,将包含在未来的版本中 - 这是对的吗?但这些功能只能通过__future__,因为它还没有成为标准 - 我是对的吗?
Python使我们能够通过在名称前加上双下划线来在类中创建"私有"方法和变量,如下所示:__myPrivateMethod().那么,如何解释这一点呢
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
Run Code Online (Sandbox Code Playgroud)
这是怎么回事?!
我会对那些没有那么做的人解释一下.
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
Run Code Online (Sandbox Code Playgroud)
我在那里做的是使用公共方法和私有方法创建一个类并实例化它.
接下来,我称之为公共方法.
>>> obj.myPublicMethod() …Run Code Online (Sandbox Code Playgroud) 我想从python中的字符串列表中删除所有空字符串.
我的想法是这样的:
while '' in str_list:
str_list.remove('')
Run Code Online (Sandbox Code Playgroud)
有没有更多的pythonic方式来做到这一点?
我认为我想做的是一项相当普遍的任务,但我在网上找不到任何参考.我有带标点符号的文字,我想要一个单词列表.
"Hey, you - what are you doing here!?"
Run Code Online (Sandbox Code Playgroud)
应该
['hey', 'you', 'what', 'are', 'you', 'doing', 'here']
Run Code Online (Sandbox Code Playgroud)
但是Python str.split()只能使用一个参数,所以在用空格分割之后,我所有的单词都带有标点符号.有任何想法吗?
使用pip,是否可以确定当前安装的软件包版本?
我知道,pip install XYZ --upgrade但我想知道是否有类似的东西pip info XYZ.如果不是什么是告诉我目前使用的版本的最佳方式.
我的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是否是同一个对象?
我有一个变量,x我想知道它是否指向一个函数.
我希望我可以这样做:
>>> isinstance(x, function)
Run Code Online (Sandbox Code Playgroud)
但这给了我:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
Run Code Online (Sandbox Code Playgroud)
我选择它的原因是因为
>>> type(x)
<type 'function'>
Run Code Online (Sandbox Code Playgroud) 我正在为本地网络编写聊天程序.我希望能够识别计算机并使用Python获取用户设置的计算机名称.