【发布时间】:2019-02-07 23:21:17
【问题描述】:
为什么dict.fromkeys 的函数描述符与其他普通函数的函数不同。
首先你不能像这样访问__get__:dict.fromkeys.__get__你必须从__dict__得到它。 (dict.__dict__['fromkeys'].__get__)
然后它不会像任何其他函数一样工作,因为它只会让自己绑定到dict。
这符合我的预期:
class Thing:
def __init__(self):
self.v = 5
def test(self):
print self.v
class OtherThing:
def __init__(self):
self.v = 6
print Thing.test
Thing.test.__get__(OtherThing())
然而这却做了一些意想不到的事情:
#unbound method fromkeys
func = dict.__dict__["fromkeys"]
但它的描述不同于普通的未绑定函数,看起来像:<method 'fromkeys' of 'dict' objects> 而不是:<unbound method dict.fromkeys> 这就是我的意思
这按预期工作:
func.__get__({})([1,2,3])
但你不能将它绑定到我理解的其他东西上它不起作用,但这通常不会阻止我们:
func.__get__([])([1,2,3])
这会因函数描述符中的类型错误而失败...:
descriptor 'fromkeys' for type 'dict' doesn't apply to type 'list'
为什么 python 会像这样区分内置类型函数和普通函数?我们也可以这样做吗?我们可以制作一个只绑定到它所属类型的函数吗?
【问题讨论】:
标签: python python-2.7 python-internals python-descriptors