这很难解释。我有一门课应该支持方法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__'没有意义。 –