小编Ben*_*Ben的帖子

当一个特定的字符串呈现给父类的构造函数Python的方式分配一个子类变量的实例

我希望能够创建父类X的实例,并使用字符串"Q"作为额外参数.
此字符串将是一个名称是用于父类X的一个子类Q上的标识符
我希望父类的实例,成为(或代替)的子类的实例.

我知道这可能是一个经典问题(错误?).经过一番搜索后,我找不到合适的解决方案.
我自己想出了以下解决方案;
我添加了一个可能的标识符字典作为其基类实例的键到父类的init -method.
然后将相应子类的 -attribute 分配给当前实例 -attribute.
我要求init -method 的参数不是默认值来防止无限循环.
以下是代码在实践中的样子示例;

class SpecialRule:
    """"""
    name="Special Rule"
    description="This is a Special Rule."
    def __init__(self, name=None):
        """"""
        print "SpecialInit"
        if name!=None:
            SPECIAL_RULES={
                "Fly" : FlyRule(),
                "Skirmish" : SkirmishRule()
                } #dictionary coupling names to SpecialRuleclasses
            self.__class__= SPECIAL_RULES[name].__class__

    def __str__(self):
        """"""
        return self.name

class FlyRule(SpecialRule):
    """"""
    name="Fly"
    description="Flies."
    def __init__(self):
        """"""
        print "FlyInit"+self.name
        SpecialRule.__init__(self)
    def addtocontainer(self, container):
        """this instance messes with the attributes of its containing …
Run Code Online (Sandbox Code Playgroud)

python subclass variable-assignment

5
推荐指数
1
解决办法
1390
查看次数

标签 统计

python ×1

subclass ×1

variable-assignment ×1