好的,显然,__new__在元类中,当元类的实例(即类对象被实例化)时运行,因此__new__在元类中提供了一个钩子来在类定义时拦截事件(/运行的代码)(例如,验证/执行类属性的规则,例如如方法等)。
元类中的许多在线示例__new__返回来自 的类型构造函数的实例__new__,这似乎有点问题,因为这会阻止__init__(文档:“如果__new__()不返回 cls 的实例,则新的实例\xe2\x80\x99s__init__()方法将不会被调用”)。
在修改元类中的返回值时,__new__我遇到了一些我不完全理解的奇怪情况,例如:
class Meta(type):\n \n def __new__(self, name, bases, attrs):\n print("Meta __new__ running!")\n # return type(name, bases, attrs) # 1. \n # return super().__new__(self, name, bases, attrs) # 2.\n # return super().__new__(name, bases, attrs) # 3. \n # return super().__new__(type, name, bases, attrs) # 4. \n # return self(name, bases, attrs) # 5.\n\n def __init__(self, …Run Code Online (Sandbox Code Playgroud) David Touretzky 的 Common Lisp 书中的练习 6.36 要求一个函数swap-first-last来交换任何列表的第一个和最后一个参数。我现在觉得很愚蠢,但我无法用destructuring-bind.
我如何在 Pythonfirst, *rest, last = (1,2,3,4)中执行 Common Lisp/with 中的操作(可迭代解包)destructuring-bind?
的Hyperspec指出mapcon是(大致λ)等价于(apply #'nconc (maplist ...)),即,“应用功能的结果被组合成通过使用nconc的而不是列表的列表”。
但如果这
(maplist #'identity '(1 2 3)) ; '((1 2 3) (2 3) (3))
(apply #'nconc '((1 2 3) (2 3) (3)))
Run Code Online (Sandbox Code Playgroud)
有效,为什么这不行
(apply #'nconc (maplist #'identity '(1 2 3)))
(mapcon #'identity '(1 2 3))
Run Code Online (Sandbox Code Playgroud)
也工作?