如何在 Python 中使用类变量作为默认参数值 [英] How to use a class variable as a default argument value in 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.x
和 MyClass.y
的重新分配,因为默认参数在创建函数时绑定一次.
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屋!