Skip to main content
 首页 » 编程设计

python之创建一个与变量相同类型的对象

2025年05月04日21del

让我们定义一些Event类:

class Event1: 
    def __init__(self, id, val1, val2): 
        self.id = id 
        self.val1 = val1 
        self.val2 = val2 
 
class Event2: 
    def __init__(self, id): 
        self.id = id 
 
class Event3: 
    def __init__(self, id, val1): 
        self.id = id 
        self.val1 = val1 

我使用一个存储事件的队列 (heapq)。为了避免使用多个 if/else 语句,我用 or 压缩了我的语句。结果是:

event = heapq.heappop(heap) 
if type(event) == Event1 or type(event) == Event2: 
    # Do stuff 
 
else: 
    # Do stuff 

我的问题是,在退出语句之前,我想重新安排一个与我的变量 event 中的事件类型相同的新事件。

即在 if 语句中:

if type(event) == Event1 or type(event) == Event2: 
    new_event = # Same type as event, either Event1 or Event2 
    # Both take the same arguments,  
    # so I do not need to bother with *arg and **kwargs. 

如何创建与变量类型相同的实例?谢谢!

请您参考如下方法:

if isinstance(event, (Event1, Event2)): 
    new_event = type(event)() 

您使用 type(event) 获取实例的类,然后使用 () 从该类实例化一个新实例。你应该使用 isinstance 而不是比较类。 isinstance 不仅可以同时与多个类进行比较,它还支持进一步的继承,即如果您曾经执行过 class Event4(Event1): pass。