Python是一个调用子类实例变量的基类

2024-04-19 22:21:07 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码。它有一个基类,该基类有一个子类,该子类从基类访问子类字段

>>> g = Base()
>>> gg = ExtendBase()
>>> for i in g:
...     print i.identification
... 
Base

它应该先打印ExtendBase,然后打印Base。为什么这样不行? 我不知道这是否是一种从基类访问子类字段的多态形式

class Base(object):
    Trackable = []
    def __init__(self, ):
        self.identification = 'Base'
        Base.Trackable.append(self)
        self.trackable = list(Base.Trackable)
    def __len__(self, ):
        return len(Base.Trackable)
    def __getitem__(self, key):
        return Base.Trackable[key]
    def __setitem__(self, key, value):
        Base.Trackable[key] = value
    def __delitem__(self, key):
        del Base.Trackable[key]
    def __iter__(self, ):
        return self
    def next(self, ):
        if self.noMoreToGo():
            self.trackable = list(Base.Trackable)
            raise StopIteration
        for item in Base.Trackable:
            if item.identification == 'ExtendBase':
                self.trackable.remove(item)
                return item
            if item.identification == 'Base':
                self.trackable.remove(item)
                return item
    def noMoreToGo(self, ):
        if self.trackable:
            return False
        else:
            return True


class ExtendBase(Base):
    def __init__(self, ):
        super(ExtendBase, self).__init__()
        self.identification = 'ExtendBase'

Tags: keyselfforbasereturnifinitdef
1条回答
网友
1楼 · 发布于 2024-04-19 22:21:07

gBase的一个实例;它不是类的所有对象的iterable,并且不包含对子类的任何元素的引用

如您所料,g.identification是“Base”,而gg.identification是“ExtendBase”。我认为你的问题在于认为g以某种方式表示基类或任何子类的所有对象

相关问题 更多 >