1

If I have 2 classes A and B, is there a way I can make an instance of class A "jump" to class B and vice versa?

I'd like to write a function for class A that, when called, essentially makes that instance of class A get reinitialized as a class B object and continue its execution as a normal instance of class B would. I'd like to make a similar function for class B. Is this possible?

3
  • Looks like code smell. Can you post your classes and explain what you are trying to achieve? Commented Dec 20, 2017 at 5:29
  • I don't like it, but I can't think of another way. I haven't created the files yet, but I'm building an autonomous capture the flag game. There are two agents on each team, a defensive and offensive one, and when one dies, I want their roles to switch. This seemed like the solution Commented Dec 20, 2017 at 5:31
  • It's a smell. A role is a property of an object, which should is assigned at run time. Allowed behaviors for different roles can be managed with object composition, or roll-your-own function tables. This really isn't a good use for class IMHO. But others may disagree. Commented Dec 20, 2017 at 5:35

1 Answer 1

2

Surprisingly, yes.

>>> class C: pass
... 
>>> c = C()
>>> type(c)
<class '__main__.C'>
>>> c.__class__
<class '__main__.C'>
>>> 
>>> 
>>> class D: pass
... 
>>> c.__class__ = D
>>> c.__class__
<class '__main__.D'>
>>> type(c)
<class '__main__.D'>

I used Python 3.6.3 to do this.

Want to see jumping in action? Check this out:

>>> class C:
...   def speak(self):
...     return "I'm a C"
... 
>>> class D:
...   def shout(self):
...     return "I'M A D"
... 
>>> c = C()
>>> c.speak()
"I'm a C"
>>> c.__class__ = D
>>> c.shout()
"I'M A D"

Python we love you, uh, I guess so.... This is weird. But cool, yeah?

How about trying an experiment on your own to see how you can preserve attributes from the original class! It's neat.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.