Is there a cool pythonic way to use a class field (class variable) as a mutable default value for a keyword argument in __init__
?
Here is the example:
class Foo():
field = 5
def __init__(self, arg=field): # arg=Foo.field => name 'Foo' is not defined
self.arg = arg
# ok, let's start
obj_1 = Foo()
print(obj_1.arg) # 5, cool
# then I want to change Foo.field
Foo.field = 10
print(Foo.field) # 10, obviously
obj_2 = Foo()
print(obj_2.arg) # still 5, that's sad :(
Why is this happening?
I know I can do smth like that:
class Qux():
field = 5
def __init__(self, arg='default'):
self.arg = {True:Qux.field, False:arg}[arg == 'default']
Qux.field= 10
obj_3 = Qux()
print(obj_3.arg) # 10
But is there a simpler way?
Thanks in advance.