A.x vs. A["x"]

Steve Holden steve at holdenweb.com
Sat Jan 23 11:05:05 EST 2010


Martin Drautzburg wrote:
> Terry Reedy wrote:
> 
>> 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,
>  
> 
>>> 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.
> 
> You're right. I used to think you could do this to classes:
> 
> G = Strum
> G.x=1
> 
> But not to objects (instances):
> 
> g = Strum()
> g.y = 2
> 
> But in fact both work. Thanks for clarifying

Both work, in fact, because a class is (like almost any other Python
object), an instance of some class. In Python the classes that are
defined in the interpreter are usually called types, but since
"new-style objects" were introduced into Python in 2.2 you can define
your own types (and subclass the system types).

The name for the particular types whose instances are classes is
"metaclass".  But once you realize that the "regular classes" you
already know about are just instances of their metaclass (the metaclass
<type 'Type'>, in many cases) it might seem less surprising.

There is a necessary but strange and surprising relationship between
types and objects that can be summarized as

  isinstance(object, type) == isinstance(type,object) == True

Because the built-in types are implemented as a part of the interpreter
they are somewhat more restricted. Consequently not only can you not add
attributes to the classes, you can't add them to the instances either:

>>> int.x = 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'int'
>>> i = int()
>>> i.y = "hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'y'
>>>

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC                 http://www.holdenweb.com/
UPCOMING EVENTS:        http://holdenweb.eventbrite.com/




More information about the Python-list mailing list