这很难解释。我有一个类应该支持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
我不知道有什么方法可以在不调用
__init__()
的情况下创建经典类的新实例(这是您在示例中使用的)。{cd2>的新实例可以使用其中
cls
是要创建的对象类型。在另一种方法是使用}来定义应该复制的内容。在
copy.copy()
进行复制,可能覆盖__getstate__()
和{编辑:要在不调用
^{pr2}$__init__()
的情况下创建经典类cls
的新实例,可以使用以下方法:请记住,每个对象都有一个名为
__class__
的属性。如果执行<object>.__class__
操作,将返回该对象的类对象(如果这有意义)。类对象是可调用的,因此您可以在末尾添加括号以创建该类的新实例。在相关问题 更多 >
编程相关推荐