在Python中,list.sort方法和sorted内置函数都接受一个名为的可选参数key,该参数是一个函数,给定列表中的元素返回其排序键.
较旧的Python版本使用了一个不同的方法,cmp而不是使用参数,这是一个函数,给定列表中的两个元素,如果第一个小于第二个,则返回负数,如果有等于则返回零,如果第一个是,则返回正数更大.在某些时候,此参数已弃用,并未包含在Python 3中.
有一天,我想以一种cmp函数比一个函数更容易编写的方式对元素列表进行排序key.我并不想这样我阅读文档,我发现有一个名为funtion使用弃用的功能cmp_to_key中functools,正如他的名字状态,接收模块cmp功能,并返回key一个......或者这就是我想直到我阅读了文档中包含的这个高级函数的源代码(或至少是等效版本)
def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K(object):
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other): …Run Code Online (Sandbox Code Playgroud) 这个命令做什么用的?
exec bash -l
Run Code Online (Sandbox Code Playgroud)
我发现这个命令是一个提醒文本文件的一部分,我写了一些关于如何创建一个ssh密钥并克隆一个git repo的说明,但是我很久以前就写过它,我不记得它做了什么.
我总是这么认为
x += y
Run Code Online (Sandbox Code Playgroud)
只是一个捷径
x = x + y
Run Code Online (Sandbox Code Playgroud)
但似乎不是列表的情况:
x = []
x2 = x
print x is x2
True
x += [2]
print x is x2
True
x = x + [2]
print x is x2
False
Run Code Online (Sandbox Code Playgroud) 当我尝试动态地向对象类的实例添加属性时,我得到一个AttributeError.但是,可以使用object的子类实例来实现.有人知道为什么吗?
>>> obj = object()
>>> obj.new_attr = "some value"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'new_attr'
>>> class MyClass(object):
... pass
...
>>> obj = MyClass()
>>> obj.new_attr = "some value"
>>> print obj.new_attr
some value
Run Code Online (Sandbox Code Playgroud) 问题是isinstance函数说datetime.datetime实例也是datetime.date的实例
为什么?那讲得通?
Python 2.7.4 (default, Sep 26 2013, 03:20:26)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> d = datetime.datetime(2014, 4, 30, 15, 9, 4, 218466)
>>> isinstance(d, datetime.datetime)
True
>>> isinstance(d, datetime.date)
True
Run Code Online (Sandbox Code Playgroud)
这使得Django 1.4.10(我没有检查其他版本)错误地提出一个RuntimeWarning说一些完全时区感知的日期时间不是,因为有一个规则(这里)说日期实例总是天真的.在django/db/models/fields/init .py,第759行引发警告.可能这是由于对"日期类型的对象总是天真的"这一短语的误解,他们应该使用类型函数比较检查类型而不是使用insinstance(甚至更好,使用django.utils.timezone.is_aware函数).
那么这是一个Django错误,还是bug是关于python isinstance函数的行为?或两者?或者只是我?
>>> from django.utils.timezone import is_aware, utc
>>> d = datetime.datetime(2014, 4, 30).replace(tzinfo=utc)
>>> is_aware(d)
True
>>> isinstance(d, datetime.date)
True
Run Code Online (Sandbox Code Playgroud)