静态方法作为类方法的默认参数 [英] static method as default parameter to a class method

查看:57
本文介绍了静态方法作为类方法的默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于另一个问题的两个答案:在同一类的方法中使用类/静态方法作为默认参数值.

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.

答案 1:使用函数代替类方法

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)

答案 2:使用类方法,但将其转换为函数

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)

这最初是用 Python 2 编写的,但我的总结是(希望是)Python 3.

This was originally written in Python 2, but my summary is (hopefully) Python 3.

推荐答案

答案实际上取决于您对 X.default_func 的其他意图.如果您打算在 X 的实例之外调用 X.default_func,那么您希望它是一个静态方法(答案 2).

The answer really depends on what other intentions you have for X.default_func. If you intend for X.default_func to be called outside of an instance of X, then you want it to be a static method (Answer 2).

# in other code...
some_object = "Bring out your dead"
X.default_func(some_object)

另一方面,如果您不希望 default_func 会被调用,除非在 X 的实例中(当然用作 test 的默认值),我会重新-将答案 1 写成合适的方法(并使用 self 的约定).

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 of self).

class X:
    def default_func(self):
        return True

    def test(self, func = default_func):
        return func(self)

作为旁注,我想指出您可以用不同的方式编写答案 2 以避免使用非静态方法:

As a side note, I'd like to point out that you could have written Answer 2 differently to avoid the unstaticmethod:

class X:
    def default_func(x):
        return True

    def test(self, func = default_func):
        return func(self)

    default_func = staticmethod(default_func)

之所以有效是因为类 X 没有被创建(并且 default_func 不会成为 X 的方法),直到 class X: 下的整个块被处理(包括默认参数对于 test(func)).

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 for test(func)).

这篇关于静态方法作为类方法的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆