如果我想在ipython中重新定义先前定义的类的成员,我想知道一个好的方法.说:我已经定义了类下面的类介绍,后来我想重新定义函数定义_print_api的一部分.没有重新输入它的任何方式.
class intro(object):
def _print_api(self,obj):
def _print(key):
if key.startswith('_'):
return ''
value = getattr(obj,key)
if not hasattr(value,im_func):
doc = type(valuee).__name__
else:
if value.__doc__ is None:
doc = 'no docstring'
else:
doc = value.__doc__
return ' %s :%s' %(key,doc)
res = [_print(element) for element in dir(obj)]
return '\n'.join([element for element in res if element != ''])
def __get__(self,instance,klass):
if instance is not None:
return self._print(instance)
else:
return self._print_api(klass)
Run Code Online (Sandbox Code Playgroud)
Dav*_*rby 12
使用%edit命令或其别名%ed.假设介绍类已经存在于ipython命名空间中,键入%ed intro将打开该类源代码的外部编辑器.当您保存并退出编辑器时,代码将由ipython执行,从而有效地重新定义了类.
这样做的缺点是,任何已经存在的实例仍然会绑定到该类的旧版本 - 如果这是一个问题,那么您需要重新创建对象或重新分配obj.class属性指向类的新版本.
您还可以%ed在模块,文件和以前的输入行上使用,例如,%ed 5 10:13 16将创建和编辑由ipython输入行5,10,11,12,13,16组成的文件.
确实没有一个“好”的方法来做到这一点。你能做的最好的事情就是这样:
# class defined as normally above, but now you want to change a funciton
def new_print_api(self, obj):
# redefine the function (have to rewrite it)
...
# now set that function as the _print_api function in the intro class
intro._print_api = new_print_api
Run Code Online (Sandbox Code Playgroud)
即使您已经定义了 intro 对象(也就是说,当您在已创建的对象上调用 introObject._print_api 时,它将调用您设置的新函数),这也将起作用。不幸的是,你仍然需要重新定义函数,但至少你不必重写整个类。
根据您的用例,最好的办法可能是将其放在单独的模块中。import类,当您需要更改某些内容时,只需使用该reload()函数即可。但是,这不会影响该类的先前实例(这可能是也可能不是您想要的)。
| 归档时间: |
|
| 查看次数: |
6159 次 |
| 最近记录: |