First of all I am new to python and a bit rusty on .NET so bear with me if this sounds too obvious. Assuming the following python classes;
class foo1(object):
def bar1(self):
print "bar1 called."
def bar2(self):
print "bar2 called."
class foo2 ..... same as above
I want to store the class methods somewhere and want to invoke them on an object of my own choosing.This is what I came up with.
ObjectOperations ops = engine.Operations;
IList<string> members = ops.GetMemberNames(scope);
foreach(string member in members)
{
if(member.StartsWith("foo"))
{
dynamic klass= scope.GetVariable(member);
dynamic instance= klass();
//for brevity I am skipping the enumeration of
//function names here.
dynamic func = ops.GetMember(instance, "bar1");//and store it somewhere
Action act = ops.ConvertTo<Action>(func开发者_Go百科); //This part is not really necessary
}
}
What I want to do is invoking the func(of type IronPython.Runtime.Method) on a instance I create sometime later. From what I glean from IronPython source that the instance is set in stone when it's created and I cannot change it.Is there a way accomplish this? I am also not sure in what context(scope??) to run the function or I shouldn't worry about it all.
ObjectOperations do have a method called MemberInvoke that takes a object and member name but I'd rather prefer MethodInfo.Invoke type of invocation both for style and performance considerations.
Any pointers would be greatly appreciated.
P.S. I am using IronPython 2.7 and .Net4.0 by the way..
Yes, this is actually very easy. In Python methods can either be invoked as bound methods such as:
x = C().f # produces a bound method
x() # invokes the bound method
Which is the same as:
C().f()
Or they can be invoked with an explicit self parameter:
C.f(C())
This works the same way from the hosting APIs, so all you need to do is something like:
dynamic klass = scope.GetVariable(member);
dynamic func = ops.GetMember(klass, "bar1");
// and then later:
func(inst);
精彩评论