我有一个班级和该班级的对象。问题是当我必须在类方法中进行更改时,我必须终止对象并启动另一个对象。有没有办法可以在不杀死对象的情况下获得修改后的功能
Class ABC:
def abc():
print "Hello I am original text"
我将班级称为
import ABC
obj = ABC()
obj.abc() is printing the desired output
如果我想在方法abc中进行更改或为类编写一个新方法,我必须重新打开python shell并有一个新的obj。
我正在寻找一种可以重新加载类的方法,同一个对象将具有该类的新属性
我正在使用Python 2.7并尝试了一些我重新加载的模块(模块)
Giving negative rating is fine but there should be a reason for that. Just like if you don't have answer to that or does not understand it well, won't qualify you to give negative rating
答案 0 :(得分:0)
好的,这是 答案。
但首先要注意一点。这样做是个坏主意。通常我会说,编写一个测试套件,编写一个模块,测试模块(硬件不会在最轻微的触摸时爆炸?)然后应用。
从this question开始。您还需要functools.partial
。
策略是编写额外的函数,就像它们是方法一样,并将猴子修补它们到对象。请注意我正在使用python 3,但这在python 2中应该可以正常工作。
我将制作两个模块。 base_class.py
和new_methods.py
。假设new_methods.py
中的每个方法都是在其他方法之后编写的,并且模块需要重新加载。
base_class.py:
class MyClass(object):
def __init__(self):
self.a = 'a'
self.b = 'b'
def show_a(self):
return self.a
new_methods.py:
def first(obj):
return obj.b
def second(obj):
return obj.a + obj.b
def third(obj, number):
return obj.a + str(number)
解释
>>> from base_class import MyClass
>>> x = MyClass()
>>> x.show_a()
'a'
>>> import sys
>>> from functools import partial
>>> import new_methods as nm
>>> x.show_a = partial(nm.first, x)
>>> x.show_a()
'b'
>>> del sys.modules['new_methods'] # wrote some new stuff. want to import
>>> import new_methods as nm
>>> x.show_a = partial(nm.third, x)
>>> x.show_a(5)
'a5'
如果使用这种方法重新加载不起作用,上面的答案非常详细,说明如何进行。
答案 1 :(得分:-1)
您可以通过使用装饰器更新方法来重新打开一个类:
---在Python 2.7 ---(不是Python 3)
a.py:
class A:
def hello(self):
print('Hello')
main.py:
from a import A
# create a decorator to reopen a class
def reopen(cls):
def updated(extend_cls):
cls.__dict__.update(extend_cls.__dict__)
return cls
return updated
a=A()
a.hello() #=> Hello
# apply the decorator and update the class
@reopen(A)
class A:
def hello(self):
print('New Hello')
def bye(self):
print('Bye bye')
a.hello() #=> New Hello
a.bye() #=> Bye bye