有没有办法像 C# 中那样为 Python 2.7 中的成员提供自定义属性?
例如,在 C# 中,我可以使用反射执行以下操作:
public class A
{
object obj1;
[MyCustumAttribute(data)]
public object Obj1Property
{ get; set; }
public A() {}
}
public static void Main(string[] args)
{
Type t = typeof(a);
PropertyInfo[] props = t.GetProperties();
attrs = props[0].GetCustomAttributes();
//Do something with the properties based on their custom attributes
}
请注意,我可以对 A 的方法、数据成员等执行相同的操作,而不仅仅是在属性上。
有没有办法在 Python 2.7 中做同样类型的事情?
For example, in C# I can do the following using reflection:
public class A
{
object obj1;
[MyCustumAttribute(data)]
public object Obj1Property
{ get; set; }
public A() {}
}
public static void Main(string[] args)
{
Type t = typeof(a);
PropertyInfo[] props = t.GetProperties();
attrs = props[0].GetCustomAttributes();
//Do something with the properties based on their custom attributes
}
Note that I can do the same thing with A's methods, data members, etc. not just on properties.
Is there a way to do this same type of thing in Python 2.7?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑:重新阅读您的问题后,我意识到反射方面没有得到解决。但据我所知,答案仍然是否定的。 .NET 反射似乎无法解决 DLR 类型(例如 IronPython、IronRuby)。不过,Python 中有一种反射机制,您可以利用它,请参阅 https://stackoverflow.com/a/1447529/635634 了解详细信息。
-
不是真的,但您可以使用 DevHawk 的解决方案。
EDIT: After re-reading your question I realized that the reflection aspect wasn't addressed. The answer is still no from what I can find though. .NET reflection doesn't seem to address DLR types (e.g. IronPython, IronRuby). There is a reflection mechanism in python that you may be able to utilize though, see https://stackoverflow.com/a/1447529/635634 for details.
-
Not really, but you can sort of achieve the same effect using DevHawk's solution.
可以帮助完成您想要实现的目标的是 python 装饰器 (有关装饰器的大量信息在此答案中)
简单地说,他们自 2.4 版起可用,并允许您包装或装饰函数 - 为了确定给定函数是否具有装饰器,您可以尝试使用 functools 库进行评估。
由于您想要装饰类,因此可以帮助您实现此目的的另一种方法是 Python 元类
Something that could help to accomplish what you are trying to achieve are python decorators (extensive info on decorators In this SO answer)
Briefly, they are available since version 2.4 and allow you to wrap or decorate a function - In order to determine if a given function has a decorator you could attempt to evaluate using the functools library.
Another way that could help you accomplish this since you want to decorate a class are Python MetaClasses