Changing The Base Class Of A Class With __new__
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.
class A(object): pass
class B(object): pass
class M(type):
def __new__(cls, clsname, bases, attribs):
# change bases
bases = (A,)
return type(clsname, bases, attribs)
class C(B):
__metaclass__ = M
some_attribute_in_c='hello'
print C.__bases__
x = C()
print isinstance(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.
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 __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:
def make_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__"