Aug-22-2019, 11:37 AM
Hi, I am for quite a long time now wondering why there is no standard
I quite often find in need for such method: for one, you need to fill an class attribute with some value that you do not want to compute for each instance (so you do not want to put it in
Now I get there are couple of "walkarounds" for this problem, like reshuffling the attribute definition in "good" order (but if you want to have class attribute with list of class methods, this will mean that you have to define method first and than the attribute). Or the "cleanest" solution to do the initialization after the definition of the class -- in such case the initialization will not have matching indent -- that can be once more "fixed" by writing separate class method to init the class and after the definition just call this method (you will be left with just one ugly line after the definition calling the class init method). And to make it work properly you also need to define
I understand that you can make all of this quite simpler with defining metaclass:
__init_class__
method (that would be called after successful definition of a method). Since 3.6 we have __init_subclass__
method which helps with most problematic so at least there is that.I quite often find in need for such method: for one, you need to fill an class attribute with some value that you do not want to compute for each instance (so you do not want to put it in
__init__
), or you want to fill an attribute with (list of) other attributes of given class.Now I get there are couple of "walkarounds" for this problem, like reshuffling the attribute definition in "good" order (but if you want to have class attribute with list of class methods, this will mean that you have to define method first and than the attribute). Or the "cleanest" solution to do the initialization after the definition of the class -- in such case the initialization will not have matching indent -- that can be once more "fixed" by writing separate class method to init the class and after the definition just call this method (you will be left with just one ugly line after the definition calling the class init method). And to make it work properly you also need to define
__init_subclass__
method that would invoke your class definition method.I understand that you can make all of this quite simpler with defining metaclass:
class ClassInitable(type): def __init__(cls, name, bases, dct): if hasattr(cls, '__init_class__'): cls.__init_class__()But if we have
__init_subclass__
why do we have to work with metaclasses to get __init_class__
?