IronPython overriding __setattr__ and __getattr__
I'm trying to implement a class in C# with a method that intercepts the Python __setattr__ and __getattr__ ma开发者_运维百科gic methods. I found this bug report:
http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=8143
But that is from 2008, and nowhere can I find ICustomAttributes or PythonNameAttribute. I don't see anything useful in Interfaces.cs either. Can someone point me in the right direction?
I don't use IronPython, so I may be completely wrong, but here is what I would suppose.
Given that Dynamic Language Runtime is now fully integrated in .NET 4.0 and IronPython is based on DLR, you should be able to use the standard .NET way of creating objects that handle setting/getting of non-existing members/attributes/properties. This can be done by implementing the IDynamicMetaObjectProvider
interface. A simpler way is to inherit from DynamicObject
, which provides default implementation for most of the methods and add only the method you need (see methods of DynamicObject):
class MyObject : DynamicObject {
public override bool TryGetMember
(GetMemberBinder binder, out object result) {
string name = binder.Name;
// set the 'result' parameter to the result of the call
return // true to pretend that attribute called 'name' exists
}
public override bool TrySetMember
(SetMemberBinder binder, object value) {
// similar to 'TryGetMember'
}
}
In C# you can use this object thanks to dynamic
. IronPython should treat it in the same way!
精彩评论