我是Python新手,所以请原谅我没有使用正确的术语。。。我使用的是python3.2,我试图弄清楚是否可以用一些声明性样式信息装饰类属性。你知道吗
在我看来是这样的:
class MyTestClass:
def __init__(self, foo):
self.foo = foo
@property
@somedeclarativeInfo("ABC",123)
def radius(self):
return self.__foo
@radius.setter
def radius(self, foo):
self.__foo = foo
我想在课堂上做两件不同的事情:
A-能够像任何其他属性一样与foo属性交互(简单的get和set)
B-能够动态地找到用这个描述符修饰的特定类的属性,并且能够提取“ABC”和123值,等等
我想也许我应该创建一个描述符来实现我想要的,但是我不确定我是否在正确的轨道上,或者这是否可以实现。你知道吗
因为我的背景是.Net,所以我用下面的例子来说明我想做什么,以防有人理解我的目标:
using System;
using System.Reflection;
namespace SampleWithProperties
{
public class MyCustomAttribute : Attribute
{
public string Val1;
public string Val2;
public MyCustomAttribute(string val1,string val2)
{
Val2 = val2;
Val1 = val1;
}
}
public class Foo
{
[MyCustomAttribute("abc","def")]
public string PropertyA { get; set; }
[MyCustomAttribute("xyz","X")]
public int PropertyB { get; set; }
public string PropertyC { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Show that we can figure out which properties have the custom attribute,
// and that we can get the values for Val1 and Val2
foreach(PropertyInfo propertyInfo in typeof(Foo).GetProperties())
{
Console.WriteLine("Found a property named "+propertyInfo.Name);
foreach(Attribute attribute in propertyInfo.GetCustomAttributes(
attributeType:typeof(MyCustomAttribute),inherit:true))
{
Console.WriteLine("Found a MyCustomAttribute on the property.");
MyCustomAttribute myCustomAttribute = attribute as MyCustomAttribute;
Console.WriteLine("Val1 = " + myCustomAttribute.Val1);
Console.WriteLine("Val2 = " + myCustomAttribute.Val2);
}
Console.WriteLine();
}
// Show that the properties can be used like normal
Foo foo = new Foo {PropertyA = "X", PropertyB = 2, PropertyC = "Z"};
Console.WriteLine("Created an instance of Foo just for fun. Its property values are "+
foo.PropertyA+","+foo.PropertyB+","+foo.PropertyC);
}
}
}
这能做到吗?你知道吗
没有简单的方法来处理属性。不能简单地对受属性保护的项设置属性或从中获取属性。你知道吗
是最简单的方法。当然,您可以始终将
value
设为属性。你知道吗如果您真的想
radius
成为一个普通属性,您可以将信息存储在dict的其他地方,并从self.propdict
或其他地方检索它。你知道吗好的,我第一次开始使用Python时写了这个问题。我现在知道如何在Python中做我发布的.Net示例代码所做的事情。诚然,当我最初发布这个问题时,我没有意识到的最大的事情是描述符改变了属性/属性的行为(不管你怎么称呼它们)。尽管如此,我们仍然可以允许这些属性像属性一样工作(并且不改变它们的行为),但是可以使用decorator为它们添加一些元数据。我目前正在实现一些协议序列化/反序列化的东西,这将派上用场。你知道吗
输出为:
相关问题 更多 >
编程相关推荐