Mathieu
Mathieu

Reputation: 5746

Create an object of the same type as a variable

Let's define a few Event class:

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

I use a queue which stores event (heapq). To avoid using multiple if / else statement, I've compacted my statement with or. The result is:

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

else:
    # Do stuff

My issue is that before exiting the statement, I want to reschedule a new event of the same type as the one from my variable event.

i.e. in the if statement:

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.

How can I create an instance of the same type as a variable? Thanks!

Upvotes: 1

Views: 91

Answers (3)

deceze
deceze

Reputation: 522081

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

You get the class of an instance with type(event), and you instantiate a new instance from that class with (). And you should use isinstance instead of comparing classes. Not only can isinstance compare to multiple classes at once, it also supports further inheritance, i.e. if you ever do class Event4(Event1): pass.

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71580

if type(event) in (Event1,Event2):
    new_event = type(event)(something)

Make it easier to check weather type(event) is Event1 or Event2

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117866

You can get the type of the object, to then initialize another object

if type(event) == Event1 or type(event) == Event2:
    new_event = type(event)(some_id)

As a side note, I generally prefer isinstance

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

Upvotes: 2

Related Questions