让我们假设类:
class Something():
def first(self):
return None
我需要用 Mock 对象替换这个类,但我需要调用或添加不存在的属性。当我尝试
fake = flexmock(Something, new_method=lambda:None)
我收到AttributeError
。
是否可以添加不存在的属性或方法?
向对象或类添加不存在的属性与 或 一样something.new_attr = some_value
简单setattr(something, 'new_attr', some_value)
。要将不存在的方法添加到对象或类,只需调用以下函数之一:
def add_method(target, method_name):
"""add class method to a target class or attach a function to a target object"""
setattr(target, method_name, types.MethodType(lambda x:x, target))
def add_instance_method(target, method_name):
"""add instance method to a target class"""
setattr(target, method_name, types.MethodType(lambda x:x, None, target))
现在,将向add_method(Something, 'new_method')
class 添加一个(虚拟)类级别的“new_method”,向类型的对象添加一个“new_method” (但不适用于 的其他实例),向类添加一个实例级别的“new_method” (即可用对于) 的所有实例。Something
add_method(something, 'new_method')
something
Something
Something
add_instance_method(Something, 'new_method')
Something
Something
注意:以上不适用于没有__dict__
属性的实例(例如内置类的实例object
)。
请检查stackoverflow上的另一个问题: 向现有对象实例添加方法