Python更新类实例以反映类方法中的变化
我在工作中更新一个类的时候,希望已经创建的类实例也能跟着更新。我该怎么做呢?
class MyClass:
""" """
def __init__(self):
def myMethod(self, case):
print 'hello'
classInstance = MyClass()
我在Maya里运行Python,软件启动时就创建了这个实例。当我调用classInstance.myMethod()时,它总是打印'hello',即使我对它进行了更改。
谢谢,
/Christian
更完整的例子:
class MayaCore:
'''
Super class and foundational Maya utility library
'''
def __init__(self):
""" MayaCore.__init__(): set initial parameters """
#maya info
self.mayaVer = self.getMayaVersion()
def convertToPyNode(self, node):
"""
SYNOPSIS: checks and converts to PyNode
INPUTS: (string?/PyNode?) node: node name
RETURNS: (PyNode) node
"""
if not re.search('pymel', str(node.__class__)):
if not node.__class__ == str and re.search('Meta', str(node)): return node # pass Meta objects too
return PyNode(node)
else: return node
def verifyMeshSelection(self, all=0):
"""
SYNOPSIS: Verifies the selection to be mesh transform
INPUTS: all = 0 - acts only on the first selected item
all = 1 - acts on all selected items
RETURNS: 0 if not mesh transform or nothing is selected
1 if all/first selected is mesh transform
"""
self.all = all
allSelected = []
error = 0
iSel = ls(sl=1)
if iSel != '':
if self.all: allSelected = ls(sl=1)
else:
allSelected.append(ls(sl=1)[0])
if allSelected:
for each in allSelected:
if nodeType(each) == 'transform' and nodeType(each.getShape()) == 'mesh':
pass
else: error = 1
else: error = 1
else: error = 1
if error: return 0
else: return 1
mCore = MayaCore()
最后一行是在模块文件里(mCore = MayaCore())。这个类里面有很多方法,所以我把它们删掉了,以便减少滚动的长度:-)
类的上面有一些导入语句,但由于某种原因,它们会影响格式。这里是:
from pymel.all import *
import re
from maya import OpenMaya as om
from our_libs.configobj import ConfigObj
if getMelGlobal('float', "mVersion") >= 2011:
from PyQt4 import QtGui, QtCore, uic
import sip
from maya import OpenMayaUI as omui
在Maya里,我们在程序启动时导入这个类和它的子类:
from our_maya.mayaCore import *
在我们写的其他工具里,我们会根据需要调用mCore.method()。我遇到的问题是,当我回去修改mCore的方法,而实例调用已经在运行时,我必须重启Maya,才能让所有实例更新到方法的更改(它们仍然会使用未修改的方法)。
3 个回答
0
我之前的回答已经解答了你最初的问题,所以我就不再重复了。不过我觉得你真正想要的是 reload
这个功能。
import our_maya.mayaCore
reload(our_maya.mayaCore)
from our_maya.mayaCore import *
在你修改了类的定义之后再使用这个功能。这样,你新添加的方法就会出现在你这个类的所有现有实例中,并且可以被使用。
0
你需要提供更多关于你正在做的事情的细节。不过,Python中的实例并不存储方法,它们总是从它们所属的类中获取方法。所以,如果你在类上修改了某个方法,已经存在的实例也会看到这个新方法。
1
好的,再试一次,这次我对问题有了新的理解:
class Foo(object):
def method(self):
print "Before"
f = Foo()
f.method()
def new_method(self):
print "After"
Foo.method = new_method
f.method()
这段代码会输出
Before
After
这个方法也适用于老式的类。关键在于修改类的内容,而不是改变类的名字。