简体   繁体   English

在Python中创建任意对象的副本并调用构造函数

[英]Creating copy of arbitrary object in Python and calling constructor

I have classes A , B , and C which inherit from Foo . 我有继承自Foo ABC类。 Their __init__ methods all do different things, but have a similar signature: they all take a single parameter i in __init__ . 他们的__init__方法都做了不同的事情,但有一个类似的签名:它们都在__init__取一个参数i Some number of instances of these classes are in a list l , and all mixed together. 这些类的一些实例位于列表l ,并且全部混合在一起。 In l , all the objects have i=1 . l ,所有对象都具有i=1

I need to go through l , and for every object I see, I need to create the same object, but instantiated with i=2 instead of i=1 . 我需要经历l ,对于我看到的每个对象,我需要创建相同的对象,但是实例化为i=2而不是i=1

How do I do this? 我该怎么做呢?

I tried this: 我试过这个:

l2 = []
for obj in l:
    obj_2 = type (obj).__init__(2)
    l2.append(obj_2)

But it didn't work. 但它没有用。

I'm not sure what you mean by "create the same object". 我不确定你的意思是“创造同一个对象”。 If you mean "create a brand-new distinct object of the same type", then try this: 如果您的意思是“创建一个全新的相同类型的独特对象”,那么试试这个:

obj_2 = type (obj)(2)

Your code, rewritten as a list comprehension: 您的代码,重写为列表理解:

l2 = [type(obj)(2) for obj in l]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM