Getting "this" to work similar to "self" in Python
Jonathan M Davis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Jul 22 15:55:27 PDT 2015
On Wednesday, July 22, 2015 22:22:00 nurfz via Digitalmars-d-learn 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! :)
Variables are not polymorphic. Only public or protected member functions are
polymorphic. If you want to override behavior in a derived class, you have
to use a function. And generally, it's not good practice to either have
member variables be public or to reuse their names in derived classes.
Making them public breaks encapsulation, and reusing names makes it too easy
to confuse which name you're dealing with.
A related question on SO:
http://stackoverflow.com/questions/31436506
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list