簡體   English   中英

如何從 __init__ 訪問在 __init_subclass__ 中創建的變量?

[英]How to access variables made in __init_subclass__ from __init__?

這是示例代碼:

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參數。 我該怎么辦?

__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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM