这动态地定义了一个新类
GentlePerson,并
p为其分配了新的类:
class Gentleman(object): def introduce_self(self): return "Hello, my name is %s" % self.nameclass Person(object): def __init__(self, name): self.name = namep = Person("John")p.__class__ = type('GentlePerson',(Person,Gentleman),{})print(p.introduce_self())# "Hello, my name is John"
根据您的要求,这会修改
p的基础,但不会更改其
p原始类
Person。因此,的其他实例
Person不受影响(并且会引发
AttributeErrorif
introduce_self的调用)。
尽管没有在问题中直接提出要求,但我将为Googlers和好奇心求助者补充说,也可以动态更改类的基础,但前提是(AFAIK)仅当该类不直接继承自
object:
class Gentleman(object): def introduce_self(self): return "Hello, my name is %s" % self.nameclass base(object):passclass Person(base): def __init__(self, name): self.name = namep = Person("John")Person.__bases__=(Gentleman,object,)print(p.introduce_self())# "Hello, my name is John"q = Person("Pete")print(q.introduce_self())# Hello, my name is Pete
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)