Search code examples
pythonpython-3.xinitializationstatic-variables

How to define a default argument in __init__ of a class that uses a static class variable?


I have an issue where I'm trying to use a static variable as a required named default argument in init of a class:

class Foo:
    bar = 1
    rab = 2
    
    def __init__(self, /, def_arg=Foo.bar):
        if def_arg == self.bar:
            pass
        elif def_arg == self.rab:
            pass

Foo()
Foo(Foo.rab)

4: NameError: name 'Foo' is not defined

I also tried without Foo. and also tried self. but it doesn't work. It has to be specifically static, so I don't want to use self.bar. Is this at all possible?


Solution

  • If you use only bar it works.

    def __init__(self, def_arg=bar):
        print(def_arg)