__new__を使用して、実行時にクラスの基本クラスを変更したいと思います。私は一生懸命に見えましたが、それを理解することができませんでした。
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'
最後の行が「hello」を返し、xが基本クラスAのCのインスタンスになるように、__ new __()に配置する適切なコードは何ですか。
追加
私のユースケースは次のとおりです。
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')
最後の行を印刷してほしい。
私はペットです。
私の種は犬です。
私の目標は、PetBuyerで動物クラスの工場のように__new __()を使用することです。これを行う理由は、構文PetBuyer('Dog')が私のプログラムで便利だからです。
ADDED2
これを行う理由は次のとおりです。私がコーディングしなければならないことは、私にとっては複雑であり、見たところ、適切なクラス設計を推測することはできません。だから私はとにかく問題をコーディングすることに頼ります。私はそれをよりよく理解するのでリファクタリングすることができます。ただし、上記の状況では、リファクタリングするのは時期尚早です。問題のいくつかのコンポーネント間の相互作用をまだ理解していません。実行時に基本クラスを変更すると、それを行うのに役立ちます。後でリファクタリングするのがより快適になります。