Ironpython:在c#定义类中区分我的方法和继承的方法的任何方法
本文关键字:方法 我的 继承 任何 中区 定义 Ironpython | 更新日期: 2023-09-27 18:09:15
我定义了一个只有一个函数的类。例如:
namespace my.namespace
{
public class MyClass
{
public void some_func(string s1, string s2)
{
// more code here
}
}
}
我可以将这个对象加载到ironpython解释器中。我想使用自省来获取仅在该类中实现的方法列表。在这个例子中,我想要一个像['some_func']
这样的列表。有办法吗?
如果我在这个实例上执行help(instance)
操作,我会得到我想要的结果:
class MyClass(object)
| MyClass()
|
| Methods defined here:
|
| __repr__(...)
| __repr__(self: object) -> str
|
| some_func(...)
| some_func(self: MyClass, s1: str, s2: str)
当然,当我输入dir(instance)
时,我得到了许多其他功能:
>>> 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']
我想知道我需要使用什么内省方法来获取该类唯一的函数列表。
你有很多选择
你可以(显式地)实现IronPython.Runtime.IPythonMembersList
接口,这样你就可以列出任何你想列出的成员。这就好像你为你的类定义了__dir__
方法。
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" };
}
}
您也可以为您的类定义一个公共__dir__
方法。返回类型实际上可以是任何类型,但您可能希望返回一些字符串集合。
public class MyClass
{
public void some_func(string s1, string s2) { }
public IEnumerable<string> __dir__()
{
return new[] { "some_func" };
}
}
你总是可以选择使用常规的。net反射。
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)
我手边没有IronPython解释器来检查它是否适用于。net类,但您可以使用:
print instance.__class__.__dict__
获取属于该类的成员。IronPython将添加一些额外的Python __foo__
方法(如__doc__
),但这些方法很容易被过滤掉。