Search code examples
pythoninheritancesubclassturtle-graphicspython-turtle

How to create a subclass in python that is inherited from turtle Module


So, i'm trying to learn python and every time i post a question here it feels like giving in...

I'm trying to make my own class of turtle.Turtle.

    import turtle
class TurtleGTX(turtle.Turtle):
    """My own version of turtle"""
    def __init__(self):
        pass

my_turtle = TurtleGTX()
my_turtle.forward(10)

Gives the Traceback: AttributeError: 'TurtleGTX' object has no attribute '_position'. Which I then learn is a "private vairable" which according to the offical python tutorial i can mangle/override in my subclass TurtleGTX. How to do this with a program as large as turtle seems rather difficult and implies i'm missing a simpler solution to the problem. In the end i learned and that was the point but i would still like to run it by the community to see if there is a elegant way to create a subclass of turtle.Turtle. (The next step is to have your turtle behave different then the standard turtle)

So a comment below made me think that maybe i could do this:

import turtle
class TurtleGTX(turtle.Turtle):
    """My own version of turtle"""


my_turtle = TurtleGTX()
my_turtle.forward(100)

which actual runs! Now i'm going to see where that leads me... something tells me that i might have gone 1 step forward two step back as this means i won't be able to initialize anything on my subclass...


Solution

  • Rounding up Ignacio's answer and orokusaki's comment you probably should write something like

    import turtle
    class TurtleGTX(turtle.Turtle):
        """My own version of turtle"""
        def __init__(self,*args,**kwargs):
            super(TurtleGTX,self).__init__(*args,**kwargs)
            print("Time for my GTX turtle!")
    
    my_turtle = TurtleGTX()
    my_turtle.forward(100)