A.x vs. A["x"]
Terry Reedy
tjreedy at udel.edu
Fri Jan 22 16:46:03 EST 2010
On 1/22/2010 2:29 PM, Martin Drautzburg wrote:
> This has probably been asekd a million times, but if someone could give
> a short answer anyways I's be most grateful.
>
> What is it that allows one to write A.x? If I have a variable A,
You do not really have a 'variable'. You have a name A bound to an
object that is an instance of class C = type(A).
> what to I have to assign to it to A.x becomes valid?
If C has the appropriate special methods for get/set/del attribute, then
you can get/set/del attributes for instances of C (such as A).
If not, you cannot.
In general, builtin classes, including object, allow get but not set/del
on both the class and instances thereof.
Subclasses of object allow all three.
> Or even further: what do I have to do so I can write A.x=1 without
> having done anything magical for x (but just for A)?
Make A be a user-defined class or an instance thereof.
> I know you can do this with classes, but not with plain objects, but why is that so?
You exact meaning here is not clear, but I suspect it is somewhat
incorrect, at least for built-in classes.
Terry Jan Reedy
More information about the Python-list
mailing list