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

后端 未结 1 420
陌清茗
陌清茗 2021-01-22 14:34

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

相关标签:
1条回答
  • 2021-01-22 15:29

    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
    
    0 讨论(0)
提交回复
热议问题