pythonpython-3.xmetaclasspython-magic

How to access variables made in __init_subclass__ from __init__?


Here is sample code:

from abc import *


class weightlayer(metaclass=ABCMeta):
    def __init_subclass__(cls):
        cls.count = 0

    def __init__(self):
        self.order = cls.count
        cls.count += 1

    @abstractmethod
    def init_weight(self):
        pass


class A_layer(weightlayer):
    def init_weight(self):
        pass


class B_layer(weightlayer):
    def init_weight(self):
        pass

I already searched it many times but I can't find the solution. My idea doesn't work because __ init __ function doesn't have the cls parameter. What should I do?


Solution

  • __init__ is an instance method, so you have to get to the actual class via the instance self:

    def __init__(self):
        self.order = self.__class__.count
        self.__class__.count += 1
    
    a1 = A_layer()
    A_layer.count
    # 1
    a1.order
    # 0
    a2 = A_layer()
    A_layer.count
    # 2
    a2.order
    # 1
    B_layer.count
    # 0