[英]Python polymorphic objects calling base class methods instead of subclass method
[英]Python — A base class calling subclass instance variables
這是我的代碼。 它具有一個基類,該基類具有一個子類,該子類可從該基類訪問子類字段。
>>> 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'
g是Base的一個實例; 它不是該類所有對象的可迭代對象,並且不包含對子類任何元素的引用。
如您所料,g.identification是“ Base”,而gg.identification是“ ExtendBase”。 我認為您的問題是認為g以某種方式代表了基類或任何子類的所有對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.