python:验证函数参数

max*_*max 2 python coding-style python-3.x

我需要确保所有命名的参数都传递给一个方法(我不想要任何默认值).以下是执行它的最佳方法吗?

class X:
  def func(self, **kwargs):
    if set(kwargs.keys() != ('arg1', 'arg2', 'arg3'):
      raise ArgException(kwargs)
Run Code Online (Sandbox Code Playgroud)

nco*_*lan 5

对于Python 2.x,Hugh的答案(即只使用命名的位置参数)是你最好的选择.

对于Python 3.x中,你也有选择需要使用的关键字参数(而不是仅仅允许它),如下所示:

class X(object):
    def func(self, *, arg1, arg2, arg3):
        pass
Run Code Online (Sandbox Code Playgroud)