可以在運行中創建子類。這並不意味着你應該。無論如何,我會提供一個機制。
的基地每班屬性告訴你的繼承鏈:
class Animal(object):
pass
class Dog(Animal):
pass
print Animal.__bases__
print Dog.__bases__
# prints:
#(<type 'object'>,)
#(<class '__main__.Animal'>,)
所以,__bases__
與「傳承基地」的元組。你可以替換這個元組(你不能「追加到它」或「從它彈出」,因爲它是一個元組,而元組是不可變的)。例如,假設你有一個「混合類」,這增加了功能的一些動物的子類而不是其他:
class Animal(object):
pass
class Dog(Animal):
pass
class Cat(Animal):
pass
class TalkMixin(object):
def talk(self):
print("I talk like a {0}".format(self.__class__.__name__))
if __name__ == "__main__":
dog = Dog()
cat = Cat()
try:
dog.talk()
cat.talk()
except AttributeError:
print("Great - the program raised AttributeError, as expected")
# now, add the MixIn to the class "Dog", but not to the class
# "Cat" - do this on the fly:
old_dog_bases = Dog.__bases__
Dog.__bases__ = (Animal, TalkMixin)
# this should be successful!
dog.talk()
try:
cat.talk()
except AttributeError:
print("As expected, cat.talk() raised AttributeError")
# now do the same (add the mixin dynamically - via inheritance) to
# the Cat
old_cat_bases = Cat.__bases__
Cat.__bases__ = (Animal, TalkMixin)
# this should be successful!
cat.talk()
# Now, remove the mixin (drop from the inheritance) for both cats
# and dogs:
Dog.__bases__ = old_dog_bases
Cat.__bases__ = old_cat_bases
try:
dog.talk()
cat.talk()
except AttributeError:
print("as expected, they can no longer talk")
產生以下輸出:
Great - the program raised AttributeError, as expected
I talk like a Dog
As expected, cat.talk() raised AttributeError
I talk like a Cat
as expected, they can no longer talk
很多人認爲混入類惡。他們可能是對的!你可以想象,如果你搞砸基地屬性,你幾乎摧毀了你的程序。所以,它是 - 你可以動態地改變一個對象的繼承,但這並不意味着你應該(可能抽象類或概念實現?)
你有沒有複習這個問題http://stackoverflow.com/questions/ 3915024 /動態創建類-python? – amirouche 2012-02-14 00:05:31
你是什麼意思的單身元類? – amirouche 2012-02-14 00:05:45
@abki我沒有。現在正在閱讀... – blz 2012-02-14 00:13:02