Reputation: 3323
I would like to use class attributes as default parameters for instance constructor, and it seems python does not support it. Could someone explain why or correct the code below so that it can work?
OK but not explicit enough from my point of view
class B:
class_size = 4
def __init__(self):
self.size = B.class_size
What I would like (does not work)
class A:
class_size = 4
def __init__(self,size = A.a_size):
self.size = size
Using the above declaration python complains:
def __init__(self,size = A.a_size): NameError: name 'A' is not defined
Upvotes: 0
Views: 57
Reputation: 168913
A
is not a name while the class namespace is being built. Just un-qualify the name (A.class_size
-> class_size
):
class A:
class_size = 4
def __init__(self, size=class_size):
self.size = size
The above does not take inheritance into account, though, should you want to override the default in a subclass. For that you're going to need to just manually look up the default value in the constructor:
class A:
default_size = 4
def __init__(self, size=None):
if size is None:
size = self.default_size
self.size = size
class B(A):
default_size = 15
print(A().size)
print(B().size)
print(B("yes").size)
outputs
4
15
yes
If None
would otherwise be a valid value for your argument, you may opt for a sentinel value instead:
NOTSET = object()
# ...
def __init__(self, size=NOTSET):
if size is NOTSET:
# ...
Upvotes: 2