【问题标题】:How to use a class variable as a default argument value in Python如何在 Python 中使用类变量作为默认参数值
【发布时间】:2019-04-30 20:08:12
【问题描述】:

我想在静态方法中使用类变量作为默认参数值。 但是当我引用这个类时,我得到一个错误NameError: name 'MyClass' is not defined

class MyClass:

    x = 100
    y = 200

    @staticmethod
    def foo(x = MyClass.x, y = MyClass.y):
        return x*y

【问题讨论】:

    标签: python class static parameter-passing static-methods


    【解决方案1】:

    当 Python 想要绑定默认参数时,MyClass 尚未定义,但 xy 已在类的范围内定义。

    换句话说,你可以这样写:

    class MyClass:
        x = 100
        y = 200
    
        @staticmethod
        def foo(x=x, y=y):
            return x*y
    

    请注意,foo不会识别对 MyCLass.xMyClass.y 的重新分配,因为默认参数在创建函数时绑定一次。

    >>> MyClass.foo()
    20000
    >>> MyClass.x = 0
    >>> MyClass.foo()
    20000
    

    【讨论】:

    • 也许值得注意的是这个问题和这个答案也适用于非静态方法?
    猜你喜欢
    • 2011-06-05
    • 2012-08-01
    • 2011-09-21
    • 2020-10-27
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多