如何在 Python 中使用类变量作为默认参数值 [英] How to use a class variable as a default argument value in Python

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

问题描述

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

class MyClass:x = 100y = 200@静态方法def foo(x = MyClass.x, y = MyClass.y):返回 x*y

解决方案

MyClass 在 Python 想要绑定默认参数时还没有定义,但是 x>y 已经在类的范围内定义.

换句话说,你可以写:

class MyClass:x = 100y = 200@静态方法def foo(x=x, y=y):返回 x*y

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

<预><代码>>>>MyClass.foo()20000>>>MyClass.x = 0>>>MyClass.foo()20000

I want to use a class variable as a default argument value in a static method. But when I reference the class, I get an error NameError: name 'MyClass' is not defined

class MyClass:

    x = 100
    y = 200

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

解决方案

MyClass is not defined yet when Python wants to bind the default arguments, but x and y are already defined in the classes' scope.

In other words, you can write:

class MyClass:
    x = 100
    y = 200

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

Note that foo will not recognize reassignments to MyCLass.x and MyClass.y because the default arguments are bound once, when the function is created.

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

这篇关于如何在 Python 中使用类变量作为默认参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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