Search code examples
pythonclassstatic-variables

Passing a static variable to a Class as argument?


How can I achieve something like this ?

class myClass(static_variable):
    static_var = static_variable

    def __init__(self, x):
        self.x = x + static_var

obj = myClass(static_variable = 3)(x = 5)
#obj.x = 8

[EDIT]
A better question would be 'How to initialize a class static variable at runtime ?', but python is interpreted so I don't know if this is a better question either.


Solution

  • Your second line will do the trick. You don't need to subsequently assign it in the constructor.

    class YourClass:
        static_var = 3*6 . # <--- assigns the static variable to a computed value, 18 in this case
        def __init__(self):
            pass
    
    instance = YourClass()
    print(instance.static_var)  # <--- this will print 18
    print(YourClass.static_var) # <--- this also prints 18