静态方法作为类方法的默认参数
我的问题是关于另一个问题的两个答案: 使用类/静态方法作为同一类方法中的默认参数值。
我试图了解这两个答案之间是否真的存在差异,如果有的话,每个答案的优缺点是什么。
问题:如何使用类方法作为同一类中方法的默认参数。
答案 1:使用函数而不是类方法
class X:
def default_func(x):
return True
def test(self, func = default_func):
return func(self)
答案 2:使用类方法,但将其转换为函数
def unstaticmethod(static):
return static.__get__(None, object)
class X:
@staticmethod
def default_func(x):
return True
def test(self, func = unstaticmethod(default_func)):
return func(self)
这最初是用 Python 2 编写的,但我的总结(希望)是 Python 3。
My question is about two answers to another question: Using class/static methods as default parameter values within methods of the same class.
I am trying to understand if there's really a difference between what the two answers do, and if so, what's the pros and cons of each.
Question: how to use a class method as a default parameter to a method in the same class.
Answer 1: use a function instead of a class method
class X:
def default_func(x):
return True
def test(self, func = default_func):
return func(self)
Answer 2: use a class method, but convert it to a function
def unstaticmethod(static):
return static.__get__(None, object)
class X:
@staticmethod
def default_func(x):
return True
def test(self, func = unstaticmethod(default_func)):
return func(self)
This was originally written in Python 2, but my summary is (hopefully) Python 3.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案实际上取决于您对 X.default_func 的其他意图。如果您打算在 X 实例之外调用
X.default_func
,那么您希望它是静态方法(答案 2)。另一方面,如果您不希望 default_func 永远不会被调用,除非在 X 的实例中(当然用作
test
的默认值),我会重写答案 1成为一个正确的方法(并使用self
约定)。作为旁注,我想指出,您可以以不同的方式编写答案 2 以避免非静态方法:
有效的原因是因为类 X 没有创建(并且 default_func 不会成为 X 的方法),直到在处理
class X:
下的整个块之后(包括test(func)
的默认参数)。The answer really depends on what other intentions you have for
X.default_func
. If you intend forX.default_func
to be called outside of an instance of X, then you want it to be a static method (Answer 2).If, on the other hand, you don't expect that default_func will ever be called except within an instance of X (and of course used as the default for
test
), I would re-write Answer 1 to be a proper method (and use the convention ofself
).As a side note, I'd like to point out that you could have written Answer 2 differently to avoid the unstaticmethod:
The reason that works is because class X isn't created (and default_func doesn't become a method of X) until after the entire block beneath
class X:
is processed (including the default argument fortest(func)
).