下面是我的代码,它适用于 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/