Square bracket and dot notations?

Asen Bozhilov asen.bozhilov at gmail.com
Sat Jun 11 10:40:21 EDT 2011


Francesco Bochicchio wrote:

> User classes - that is the ones you define with the class statement -
> can implement support for the squared bracket and
> dot notations:
> -  the expression myinstance[index] is sort of translated into  of
> myinstance.__getitem__(index)
> -   the expression myinstance.myattribute is sort of translated of
> myinstance.__getattr__("myattribute")

It is exactly what I wanted to know. Thank you. I have not examined
classes in Python yet, but when I do it I will understand some new
things. One of the most interesting is, can an object inherit items
trough the parent class? By items I mean items which are accessible
trough square bracket notation.

I really like Pythonic way here. Square bracket and dot notations
allow me to create an object which can be "true" hash map and
meanwhile to support independent methods from its keys. I could have
an item and a property with same names and they won't interfere each
other.

> Classes also exposes a __dict__ attributes that allows to access to
> instance attributes and methods using dictionary
> semantics. That is, myistance.__dict__["myattribute"]  should give the
> same result as  myinstance.myattribute.
> I believe this is because in the beginning class instances actually
> had a dictionary storing the instance attributes.
> Nowadays it is more complex than that, I think,  but the interface is
> kept to allow dynamic access to instance contents,
> although the reccomended way to do it this is getattr(myinstance,
> "myattribute"). Of course it is only useful to use __dict__
> or getattr when the parameter is not a constant string but a variable
> referring to a string computed at run time  (  this is
> what I mean for 'dynamic access' ).

Yeah, I agree with that. For example in JS exactly square bracket
notation has been invented to dynamic property access. The biggest
question here is why do you need dynamic property access? In language
as JavaScript which is strongly bounded to browser environment, you
could use:

function getForm(formName) {
    return document.forms[formName];
}

Another use case is to call a method of object and kept the proper
`this' value. E.g.

obj.x = 10;
obj.method = function () {
    return this.x;
};

function callMethod(obj, method) {
    return obj[method]();
}

callMethod(obj, 'method'); //10

Of course it could be achieved in different ways and with dot notation
of course.

Thank you very much for the answer.



More information about the Python-list mailing list