1

这是示例代码:

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

我已经搜索了很多次,但我找不到解决方案。我的想法不起作用,因为__ init __函数没有cls参数。我应该怎么办?

4

1 回答 1

1

__init__是一个实例方法,所以你必须通过实例到达实际的类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
于 2021-10-25T12:26:02.413 回答