ironpython: any way to distinguish my methods from inherited methods in c# defined class?
I have defined a class with a single function. For example:
namespace my.namespace
{
public class MyClass
{
public void some_func(string s1, string s2)
{
// more code here
}
}
}
I am able to load this object into an ironpython interpreter. I want to use introspection to get a list of methods that were implemented only in this class. In this example I want a list like ['some_func']
. Is there a way to do it?
If I do a help(instance)
on this instance I get more-or-less what I want:
class MyClass(object)
| MyClass()
|
| Methods defined here:
|
| __repr__(...)
| __repr__(self: object) -> str
|
| some_func(...)
| some_func(self: MyClass, s1: str, s2: str)
Of course, when I d a dir(instance)
I get a lot of other functions:
>>> dir(instance)
['Equals', 'GetHashCode', 'GetType', 'MemberwiseClone', 'ReferenceEquals', 'ToString', '__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'some_func']
I want to know what instrospection method I need to use to get a list of only the functions unique t开发者_开发知识库o this class.
You have a number of options.
You can (explicitly) implement the IronPython.Runtime.IPythonMembersList
interface that way you can list whatever members you want to list. It's as if you defined the __dir__
method for your class.
public class MyClass : IronPython.Runtime.IPythonMembersList
{
public void some_func(string s1, string s2) { }
IList<object> IronPython.Runtime.IPythonMembersList.GetMemberNames(CodeContext context)
{
return new[] { "some_func" };
}
IList<string> Microsoft.Scripting.Runtime.IMembersList.GetMemberNames()
{
return new[] { "some_func" };
}
}
You could always define a public __dir__
method for your class as well. The return type could be anything really, but you'll probably want to return some collection of strings.
public class MyClass
{
public void some_func(string s1, string s2) { }
public IEnumerable<string> __dir__()
{
return new[] { "some_func" };
}
}
You always have the option to use regular .NET reflection.
from System.Reflection import BindingFlags
# you can omit the flags if you want all public .NET members
flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly
members = instance.GetType().GetMembers(flags)
dir_members = [ mi.Name for mi in members ]
print(dir_members)
I don't have an IronPython interpreter handy to check if it works with .NET classes, but you can use:
print instance.__class__.__dict__
to get the members that are just part of that class. There will be some extra Python __foo__
methods (like __doc__
) that IronPython adds but those are easy to filter out.
精彩评论