Getting "this" to work similar to "self" in Python
nurfz via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Jul 22 15:22:00 PDT 2015
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! :)
More information about the Digitalmars-d-learn
mailing list