是否可以将基类添加到对象实例(不是类!)在运行时?类似于Object#extend
在Ruby中的工作原理:
class Gentleman(object):
def introduce_self(self):
return "Hello, my name is %s" % self.name
class Person(object):
def __init__(self, name):
self.name = name
p = Person("John")
# how to implement this method?
extend(p, Gentleman)
p.introduce_self() # => "Hello, my name is John"
稍微干净的版本:
虽然已经有答案了,但这里有一个函数:
这将动态定义一个新类
GentlePerson
,并将p
的类重新分配给它:根据您的请求,这将修改
p
的基,但不会更改p
的原始类Person
。因此,Person
的其他实例不受影响(如果调用introduce_self
,则会引发AttributeError
)。虽然在这个问题中没有直接问到这个问题,但是我要补充的是,对于Google和好奇者来说,也可以动态地改变一个类的基,但是(AFAIK)只有当这个类没有直接从
object
继承时:相关问题 更多 >
编程相关推荐