python - 向类添加方法在 python3.7.0 中不起作用同样适用于 python 2.7

标签 python python-3.x python-2.7

下面是我的代码,它适用于 python 2 而不是 python 3, 添加了一些小的更改以使语法与 python3 兼容。 请帮忙解决这个问题。 我得到的错误是

TypeError: get() missing 1 required positional argument: 'self'

import collections
from types import MethodType

_ApiMethod = collections.namedtuple('_ApiMethod', ['name', 'path', 'http_method', 'query_params'])

API = [
    _ApiMethod('print_hello', 'api/hello', "GET", ['limit']),

]

class HelloClient(object):

    def __repr__(self):
        return "HelloClient(%s)" % ', '.join('%s=%s' % (a, repr(getattr(self, a))) for a in ['url', 'headers'])

    def get(self, path,query_params=None, headers=None, **kwargs):

        return "I am Hello Get Method"


def _add_methods():

    def _build_method(path, http_method, expected_query_params):

        if http_method == "GET":

            def _method(self, **kwargs):
                query_params = kwargs.setdefault('query_params', {})
                query_params.update({qp: kwargs[qp] for qp in expected_query_params if qp in kwargs})
                return self.get(path=path, **kwargs)

        return _method

    for api_method in API:        
        setattr(HelloClient, api_method.name, MethodType(_build_method(api_method.path, api_method.http_method, api_method.query_params or []), HelloClient))

_add_methods()

我会把这个方法称为

client = HelloClient()
response = client.print_hello()

最佳答案

这里的主要问题是你混合了旧的 unbound methods来自 python 2,在 python 3 中被丢弃。 由于 python 3 类不再将其函数公开为 unbound methods ,运行以下代码段:

class A:
  def f(self):
    pass

type(A.f)

给出 function在 python 3 和 <type 'instancemethod'> 中在 python 2。通过 python 3 中的这种简化,类不再具有处理 MethodType 的正确机制。如您所料。

解决方案是向类中添加一个简单的函数(_build_method 结果)。


此特定情况下的解决方案将发生变化:

setattr(HelloClient, api_method.name, MethodType(_build_method(api_method.path, api_method.http_method, api_method.query_params or []), HelloClient)

进入:

setattr(HelloClient, api_method.name, _build_method(api_method.path, api_method.http_method, api_method.query_params or [])

关于python - 向类添加方法在 python3.7.0 中不起作用同样适用于 python 2.7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54018060/

相关文章:

python-3.x - 如何通过 SOAP API 锁定 virtualbox 以获取屏幕截图

python - 如何比较 Python 中的枚举?

Python 共享值

python - 如果条件为真,则创建具有相邻列表元素的元组列表

python - Errno 10060 连接尝试失败

python - 使用 subprocess 模块会释放 python GIL 吗?

python - 检查 python 3 支持的要求

未收到 Internet 上的 Python 套接字

python - 在 Pandas 中用 NaN 替换多列中的多个字符串和数字

python-2.7 - 如何在 numpy 中计算分数的 pow 或 n 次方根?