Getting "this" to work similar to "self" in Python

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 22 15:52:20 PDT 2015


On Wednesday, 22 July 2015 at 22:22:02 UTC, nurfz wrote:
> How could I get this D code to work similar to this Python code?
>
> So, here is the D code:
>
>     import std.stdio;
>
>     class Vehicle {
>         int speed;
>         void printSpeed() {
>             writeln(this.speed);
>         }
>     }
>
>     class Airplane: Vehicle {
>         int speed = 100;
>     }
>
>     int main() {
>         auto v = new Vehicle();
>         auto a = new Airplane();
>
>         v.printSpeed();  // 0
>         a.printSpeed(); // 0 not 100
>
>         writeln(v.speed); // 0
>         writeln(a.speed); // 100
>     }
>
> Here is the Python code:
>
>     class Vehicle:
>         speed = 0
>         def printSpeed(self):
>             print(self.speed)
>
>     class Airplane(Vehicle):
>         speed = 100
>
>     if __name__ == "__main__":
>         v = Vehicle()
>         a = Airplane()
>
>         v.printSpeed()  # 0
>         a.printSpeed()  # 100
>
>         print(v.speed)  # 0
>         print(a.speed)  # 100
>
> I guess I'm confused as to why the D code isn't acting similar 
> to the Python code in the sense that you would expect "this" to 
> reference the "speed" property of the current instance and not 
> statically reference the parent.  Am I having these issues 
> because these attributes are being initialized statically?
>
> Would using constructors be the way to go about this? I suppose 
> I'm just trying to find a way to implement fairly clean and 
> intuitive object oriented inheritance that isn't crippled by 
> getters/setters, is resolved at compile time, and doesn't 
> impose any kind of runtime cost other than what you would 
> assume is associated with fundamental level OOP.
>
> Sorry for the long winded post, but this has just been 
> confusing me to no end.  Hopefully you guys can help me out! :)

Fields of classes are not in any way polymorphic in D (this is 
the same as C++ and I think java too). Base class members can be 
accessed like so:

class Vehicle {
     int speed;
     void printSpeed() {
         writeln(this.speed);
     }
}

class Airplane: Vehicle {
     this()
     {
         Vehicle.speed = 100;
     }
}

or if you really want to use the same variable name:

class Airplane: Vehicle {
     alias speed = Vehicle.speed;
     this()
     {
         speed = 100;
     }
}

You can even automatically do that sort of thing by various 
means, the shortest/simplest way I can think of would be:

class Airplane: Vehicle {
     private @property Vehicle base() { return this; }
     alias base this;
     this()
     {
         speed = 100;
     }
}


More information about the Digitalmars-d-learn mailing list