[Python.NET] attribute semantics question
brian at zope.com
Wed Jun 15 15:38:13 CEST 2005
> It is currently possible to add new attributes using the standard python
> notation, to existing C# objects.
> like that:
> #C is C# class
> cInstance = C()
> c.NewProperty = "hop" #NewProperty Property is not defined at the
> C# level.
> My questions:
> 1: is this the desired/expected behaviour?
> 2: is this usable at C# level (I should test, I suppose, using
> introspection ;-)
> --> I find it sometimes annoying not to know that I am defining a new
> attribute, because such dynamicity is not expected at C# level (well at
> python level).
Hi Stan -
Instance of managed class have Python semantics, meaning that you
can set arbitrary attributes on the instance. If the attribute maps
to a true managed attribute (field, property, etc.) then the value
will be visible to managed code. *New* attributes are not visible
to managed code -- there's really no way they could be, since most
managed languages depend on the compile-time definition of a type
and could rarely do anything useful with a dynamic attribute.
The same holds true for Python sub-classes of managed types, which
is the main way that extra (Python-only) attributes would be added:
from CLR.System.Drawing import Point
self.Z = 0
In this case, managed code cannot see or use MyPoint.Z. It cannot
see MyPoint at all, in fact -- an instance of MyPoint passed to a
managed method will be seen by managed code as a Point instance.
Subclassing is a case where technically we *could* be fancy and
generate a managed subclass visible to the managed world if we
worked hard enough. So far, I'm not convinced that its worth the
work, given that the usefulness would be limited (again, because
most managed languages work against compile-time metadata, a
Python-generated managed subclass wouldn't really be useful for
defining new types unless it could be persisted to an assembly
for other managed code to build against).
Brian Lloyd brian at zope.com
V.P. Engineering 540.361.1716
Zope Corporation http://www.zope.com
More information about the PythonDotNet