如何在Python的静态方法中将类变量作为默认值传递 [英] How to pass a class variable as a default value in a static method in Python

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

问题描述

我想将类变量作为默认值传递给静态方法。
但是,当我导入该类时,出现错误 NameError:未定义名称'MyClass'

  class MyClass:

x = 100
y = 200

@staticmethod
def foo(x = MyClass。 x,y = MyClass.y):
返回x * y


解决方案<当Python想要绑定默认参数时,/ div>

MyClass 尚未定义,但是 x y 已经在类的范围中定义。



换句话说,您可以编写:

  class MyClass:
x = 100
y = 200

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

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

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


I want to pass a class variable as a default value to a static method. But when I import 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天全站免登陆