How to pass a class variable as a default value in a static method in Python

吃可爱长大的小学妹 提交于 2019-12-02 04:54:01

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/53527546/how-to-pass-a-class-variable-as-a-default-value-in-a-static-method-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!