這很難解釋。我有一門課應該支持方法copy_stateonly()
。它應該返回一個殘缺版本的對象,它只包含我想要的(複製的)數據成員。我希望這個例子更好解釋的那樣:動態創建類型爲(self)的實例而不調用__init__?
# everything inherits from this
class SuperBase:
def __init__(self):
self.state_var = 3 # this should be copied into future objects
self.non_state_var = 0 # we don't want to copy this
def copy_stateonly(self):
newobj = # ??????????? create instance without calling __init__
newobj.state_var = self.state_var
return newobj
# some clases inherit from this
class Base(SuperBase):
def __init__(self):
SuperBase.__init__(self)
self.isflying = True # we want to copy this, this is state
self.sprite = "sprites/plane_generic.png" # we must drop this
def copy_stateonly(self):
newobj = SuperBase.copy_stateonly(self)
newobj.isflying = self.isflying
return newobj
class A144fighter(Base):
def __init__(self, teamname): # note required __init__ argument
Base.__init__(self)
self.colors = ["black", "grey"] # we want to copy this, this is state
self.name = teamname # we must drop this
def copy_stateonly(self):
newobj = Base.copy_stateonly(self)
newobj.colors = self.colors[:]
return newobj
plane = A144fighter("team_blue")
plane_state = plane.copy_stateonly() # this should return an A144fighter object with only state_var, flying and colors set.
的Python 2.7
無需破解:'進口類型; types.InstanceType(cls)'(或'import new; new.instance(cls)') –
第二種方法只適用於兩個類具有相同佈局的情況,這對大多數類來說都是正確的,但不會是,例如,每個班級使用'__slots__'。 – SingleNegationElimination
@TokenMacGuy:正如我所說的,第二種方法只適用於* classic *類。在這種情況下'__slots__'沒有意義。 –