这很难解释。我有一个应该支持方法copy_stateonly()
的类。它应该返回一个残缺的对象版本,它只包含我想要的(复制的)数据成员。我希望这个例子更好地解释它:
# 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
答案 0 :(得分:7)
我不知道如何在不调用__init__()
的情况下创建经典类的新实例(这是您在示例中使用的)。可以使用
object
的后代)
object.__new__(cls)
其中cls
是您要创建的对象类型。
另一种方法是使用copy.copy()
进行复制,可能会覆盖__getstate__()
和__setstate__()
来定义应该复制的内容。
修改:要创建经典类cls
的新实例而不调用__init__()
,您可以使用以下黑客:
class EmptyClass:
pass
new_instance = EmptyClass()
new_instance.__class__ = cls
new_instance.__dict__.update(whatever)
答案 1 :(得分:2)
# 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 __getstate__(self):
return { 'state_var' : self.state_var }
def __str__(self):
return self.__class__.__name__ + '(' + str(vars(self)) + ')'
# 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 __getstate__(self):
state = SuperBase.__getstate__(self)
state['isflying'] = self.isflying
return state
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 __getstate__(self):
state = Base.__getstate__(self)
state['colors'] = self.colors[:]
return state
plane = A144fighter("team_blue")
print plane
import copy
print copy.copy(plane)
# or manually:
import types
print types.InstanceType(plane.__class__, plane.__getstate__())
答案 2 :(得分:1)
请记住,每个对象都有一个名为__class__
的属性。如果你<object>.__class__
它,它将返回该对象的类对象(如果这是有意义的)。类对象是可调用的,因此您可以在末尾添加括号以创建该类的新实例。
newobj = self.__class__()