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...

有帮助吗?

解决方案

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)

其他提示

If you redefine a method (such as __init__()) in a child class then it is your responsibility to call the parent's method in order to have the parent's behavior respected.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top