将对象转换为新类

2024-05-16 19:33:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两门非常相似的课。ExampleWithASurprise继承自Example,具有一个以上属性。我的示例存储了从它们的创建到我将它们转换为dict的那一刻之间的所有示例

my_examples = []


class Example:
    def __init__(self, stuff, morestuff):
        my_examples.append(self)
        self.stuff = stuff
        self.stiff = 10 + morestuff

    def to_dict(self):
        return {"stuff": self.stuff, "stiff": self.stiff}


class ExampleWithASurprise(Example):
    def __init__(self, surprise, *args):
        Example.__init__(self, *args)
        self.surprise = surprise

    def to_dict(self):
        res = Example.to_dict(self)
        res["surprise"] = self.surprise
        return res

_ = Example("egg", 10)
_ = ExampleWithASurprise("surprising surprise", "bacon", 5)
for e in my_examples:
    print(e.to_dict)

问题是,我想要一种方法将一个带有惊奇的例子转化为一个常规的例子(一旦发现了惊奇)。我可以在ExampleWithPrise中添加一种方法:

class ExampleWithASurprise(Example):
    def __init__(self, surprise, *args):
        Example.__init__(self, *args)
        self.surprise = surprise

    def to_dict(self):
        res = Example.to_dict(self)
        res["surprise"] = self.surprise
        return res

    def remove_surprise(self):
        my_examples.remove(self)
        _ = Example(self.stuff, self.stiff-10)


ex1 = Example("egg", 10)
ex2 = ExampleWithASurprise("surprising surprise", "bacon", 5)
ex2.remove_surprise()
for e in my_examples:
    print(e.to_dict())

惊喜很容易就消除了,这正是我想要的。然而,这个remove_惊奇的方法很快就会变得不可能维护:在这个示例中,我所做的唯一操作是添加10,这很容易逆转,但是我感兴趣的实际类的操作比它们的参数更复杂

正确的方法是怎样将一个带有惊奇的例子转换成一个简单的例子,这样to_dict就可以正确地工作,而不会列出惊喜


Tags: to方法selfinitexamplemydefargs