Just some questions about OOP and setter


https://github.com/tjfehdgns1/Questions/blob/main/OOP.gd , <- code link

 I was just trying with concepts of OOP, not really perfectly suits in Godot but just for understanding. 

023-10-05 174318.png


1. Is this right(?) concept of oop? anything wrong in my code?

Main class

023-10-05 170849.png

Vehicle class

023-10-05 170854.png

print("%s window open" %model) # wont work if model in class vehicle is private ?

2. If model is private can't read from subclass? so should use getter?

Driver class

023-10-05 170858.png

3. why this setter won't work? 


023-10-05 165334.png

res://OOP.gd:66 - Parse Error: Function "_set_driver" cannot be used as setter because of its signature.

1 love
  • Nathan Lovato replied


    1. Your code looks fine, except for one part. So first, GDScript doesn't have the notion of "private". Instead, we often use a leading underscore character (_) to indicate that a method or property is meant to be private (it should not be used outside of the class's code). But here, you're calling these pseudo-private setter functions from outside their class definitions: car._set_vehicle()

    If that's intentional, then the convention would be to rename the method into set_vehicle(), without the leading underscore.

    2. Nothing is private in GDScript, so that's not applicable to GDScript.

    3. A setter function should always have only one argument: the new value to assign to the variable.


    export var grid_width := 3 setget set_grid_width
    func set_grid_width(new_width: int) -> void:
        grid_width_width = new_width

    The function set_grid_width takes only one argument and assigns it to the property.

    In GDScript, you don't use the things you may see in other languages like self or this to explicitly tell the computer that it should operate on an instance of the class. They're implied: every GDScript file is a class.

    Note that if you haven't already, I would recommend taking Learn to Code From Zero with Godot 3, which covers a lot of this and teaches you a lot of decent programming practices in ways more concrete than OOP principles. OOP principles are often abstract and... if you follow the canonical OOP style strictly, it can really make your code overly complicated. It takes a good amount of experience to use this programming paradigm efficiently.

    I hope this helps!

    2 loves