Python Forum
Why is there no __init_class__ method
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why is there no __init_class__ method
#1
Hi, I am for quite a long time now wondering why there is no standard __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__?
Reply
#2
** Please Note **
python-forum.io is not python.org, and is not the author of python

define all of the variables you need to use in other methods using self.name
they will then be visible to methods in the class, and also visible outside of the class if prefixed by the class name
There is no need for another __init__ unless using inheritance

example:
class alpha1:
    def __init__(self):
        self.prog_name = f"Program name: {__file__}"
    
    def show_name(self):
        print(f"\nIn show_name: {self.prog_name}\n")

class beta1:
    def __init__(self):
        a = alpha1()
        # print variable direct
        print(f"\nalpha1.prog_name: {a.prog_name}\n")
        # or by calling method of class
        print('\nBy calling method show_name:')
        a.show_name()

if __name__ == '__main__':
    beta1()
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020