【问题标题】:How to access variables made in __init_subclass__ from __init__?如何从 __init__ 访问 __init_subclass__ 中的变量?
【发布时间】:2021-12-10 22:28:25
【问题描述】:

这里是示例代码:

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 参数。 我该怎么办?

【问题讨论】:

    标签: python python-3.x metaclass python-magic


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 1970-01-01
      • 2022-06-26
      • 1970-01-01
      • 2021-05-16
      • 2011-01-16
      • 2012-11-14
      • 2013-08-18
      • 1970-01-01
      相关资源
      最近更新 更多