python 类的前向声明

https://stackoverflow.com/questions/4162456/forward-declaration-of-classes?rq=1

class Base:
    pass
#   subs = [Sub3,Sub1]
# Note that this is NOT a list of all subclasses!
# Order is also important

class Sub1(Base): pass
class Sub2(Base): pass
class Sub3(Base): pass


class Base(object):  # New-style class (i.e. explicitly derived from object).

    @classmethod
    def register_subclass(cls, subclass):
        """ Class decorator for registering subclasses. """

        # Replace any occurrences of the class name in the class' subs list.
        # with the class itself.
        # Assumes the classes in the list are all subclasses of this one.
        # Works because class decorators are called *after* the decorated class'
        # initial creation.
        while subclass.__name__ in cls.subs:
            cls.subs[cls.subs.index(subclass.__name__)] = subclass

        return cls  # Return modified class.

    subs = ['Sub3', 'Sub1']  # Ordered list of subclass names.


@Base.register_subclass
class Sub1(Base): pass
posted @ 2021-10-14 14:57  ijpq  阅读(532)  评论(0编辑  收藏  举报