functools.partialmethod和classmethod的组合

时间:2016-09-05 14:23:31

标签: python python-3.x python-3.5 class-method functools

我想在classmethod上使用functools.partialmethod。然而,我找到的行为并不是我所期望的(并且喜欢)。 这是一个例子:

class A(object):
    @classmethod
    def h(cls, x, y):
        print(cls, x, y)

class B(A):
    h = functools.partialmethod(A.h, "fixed")

当我这样做时

>>> b = B()
>>> b.h(3)

我收到错误:

...
TypeError: h() takes 3 positional arguments but 4 were given

这与

一致
>>> b.h()
<class '__main__.A'> <__main__.B object at 0x1034739e8> fixed

但是,我希望(并且喜欢)以下行为:

>>> b.h(4)
<class '__main__.B'> fixed 4

我认为functools.partialmethodB.h视为普通实例方法,并自动将实际实例作为第一个参数传递。 但是这种行为使functools.partialmethod无法用于冻结继承类的类方法中的参数。

2 个答案:

答案 0 :(得分:2)

{@ 1}}对象与partial用于创建类实例的描述符协议不能很好地混合。简单的解决方法是以通常的方式定义重写方法:

@classmethod

可能可以通过调用class B(A): @classmethod def h(cls, y): return A.h("fixed", y) 来执行您想要的操作,但我无法找到它。以下是我的一些尝试,以及他们失败的原因。

partial调用函数对象的A.h方法,返回一个函数,其中第一个参数已绑定到调用类。然后__get__将该函数应用于partial,但结果可调用的仍然有一个"fixed"方法,该方法尝试将调用类插入到结果调用中。您可以尝试通过将__get__定义为实际上是静态方法来解决此问题:

h

但正如您所看到的,当您致电class B(A): h = staticmethod(partial(A.h, "fixed")) >>> B.h(4) <class '__main__.A'> fixed 4 时,您已经冻结了阶级参数。另一种尝试是通过直接访问参数来避免描述符协议:

partial

class B(A): h = staticmethod(partial(A.__dict__["h"], "fixed")) 个对象实际上不可调用;只有classmethod方法的返回值,因此对__get__的调用失败。

答案 1 :(得分:1)

使用super(v2.7)

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()

super is super