Skip to content Skip to sidebar Skip to footer

Changing The Base Class Of A Class With __new__

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

Solution 1:

When you are overriding __new__ that class is already in existence, anyway __new__ is used to create instances of a given class, what you want can be done via a metaclass, which can act like a factory for classes

e.g.

classA(object): passclassB(object): passclassM(type):
    def__new__(cls, clsname, bases, attribs):
        # change bases
        bases = (A,)
        returntype(clsname, bases, attribs)

classC(B): 
    __metaclass__ = M    
    some_attribute_in_c='hello'print C.__bases__
x = C()
printisinstance(x, A)
print x.some_attribute_in_c

output:

(<class'__main__.A'>,)
True
hello

After seeing OP's edit I will say forget all of the above, you don't need any metaclass, just a simple PetBuyer class which is composed of (has a) Pet , so question is why can't you just pass the pet to PetBuyer e.g.

classPet(object):
    some_attribute_in_pet='I\'m a pet.'classDog(Pet):
    some_attribute_in_species='My species is dog.'classCat(Pet):
    some_attribute_in_species='My species is cat.'classPetBuyer(Pet):

    def__init__(self, pet):
        self.pet = pet

        print self.pet.some_attribute_in_pet
        print self.pet.some_attribute_in_species

x = PetBuyer(Dog())

I also do not understand why you need to change the class of PetBuyer, is bad design IMO

Solution 2:

Based on your new information, it sounds like you need to create types dynamically. You certainly are not obligated to create a class suite to describe those types, you can create them at run time by calling the type function directly:

defmake_thingy(bases):
    new_thingy_class = type("???", bases, {})
    new_thingy_instance = new_thingy_class()
    print new_thingy_instance.some_attribute_in_pet
    print new_thingy_instance.some_attribute_in_species
    return new_thingy_instance

x = new_thingy(Dog)

Post a Comment for "Changing The Base Class Of A Class With __new__"