Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a class variable as a default argument value in Python

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
like image 743
Miguel Manjarrez Avatar asked Jan 02 '23 13:01

Miguel Manjarrez


1 Answers

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
like image 60
timgeb Avatar answered Jan 04 '23 04:01

timgeb