I would like to change the base class of a class at runtime using __new__. I looked as hard as I could, but I couldn't figure it out.
class A(object): pass
class B(object): pass
class C(B):
some_attribute_in_c='hello'
def __new__(cls):
cls.__bases=(A,) #some code here to change the base class
return super(C,cls).__new__(A)
x=C()
x.some_attribute_in_c #return Error: x has no attribute 'some_attribute_in_c'
What is the proper code to put in __new__() so that the last line return 'hello' and x is an instance of C with base class A.
ADDED
My use case is the following.
class Pet(object):
some_attribute_in_pet='I\'m a pet.'
class Dog(Pet):
some_attribute_in_species='My species is dog.'
class Cat(Pet):
some_attribute_in_species='My species is cat.'
class PetBuyer(Pet):
def __new__(cls,desired_animal):
animal_bought=globals[desired_animal]
cls.__bases=(animal_bought,) #some code here to change the base class
return super(PetBuyer,cls).__new__(animal_bought)
def __init__(self,desired_animal):
print self.some_attribute_in_pet
print self.some_attribute_in_species
x = PetBuyer('Dog')
I would like the last line to print.
I'm a pet.
My species is dog.
My goal is to use __new__() in PetBuyer like a factory for the animals class. My reason for doing this are that the syntax PetBuyer('Dog') is convenient in my program.
ADDED2
My reason for doing this is the following. What I have to code is complex for me in the sense that, per see, I cannot infer the proper class design. So I resort to code my problem in anyway I can an refactor as I better understand it. However, with the situation that arise above, it will be too early for me to refactor. I have yet to understand the interaction between some components of my problem, and changing the base class at runtime will help me to do it. I will be more comfortable for refactoring afterward.