Arguments and attributes with the same name

bearophile bearophileHUGS at lycos.com
Thu Mar 4 08:49:13 PST 2010


Steven Schveighoffer:
> I think the point is, the statement x = x + 1; isn't any more or less  
> ambiguous in D than it is in python.  There is a well-defined meaning (and  
> in fact the same meaning).

It's not the same meaning, this program prints "1":

import std.c.stdio: printf;
class Foo {
    int x;
    this() {}
    void foo() {
        x = x + 1;
    }
}
void main() {
    Foo f = new Foo();
    f.foo();
    printf("%d\n", f.x); // prints 1
}

An equivalent Python program with "x = x + 1;" prints:
UnboundLocalError: local variable 'x' referenced before assignment
Because the usage of "self." is obligatory.

Anyway, this whole thread is not about Python, it's about D.

Bye,
bearophile



More information about the Digitalmars-d mailing list