在不调用__init__的情况下动态创建类型(self)的实例?

orl*_*rlp 5 python copy class

这很难解释.我有一个应该支持该方法的类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.
Run Code Online (Sandbox Code Playgroud)

Python 2.7

Sve*_*ach 7

我不知道如何在不调用的情况下创建经典类的新实例(这是您在示例中使用的)__init__().object可以使用创建新样式类(后代)的新实例

object.__new__(cls)
Run Code Online (Sandbox Code Playgroud)

cls您要创建的对象的类型在哪里.

另一种方法是copy.copy()用于复制,可能覆盖__getstate__()__setstate__()定义应该复制的内容.

编辑:要在cls不调用的情况下创建经典类的新实例__init__(),可以使用以下hack:

class EmptyClass:
    pass

new_instance = EmptyClass()
new_instance.__class__ = cls
new_instance.__dict__.update(whatever)
Run Code Online (Sandbox Code Playgroud)

  • 第二种方法只有当两个类具有相同的布局时才有效,对于大多数类来说都是如此,但是例如,当任何一个类使用`__slots__`时都不会. (2认同)