首页 > 解决方案 > 乌龟的python子类

问题描述

我正在尝试创建一个继承海龟在python中的方法的子类。我的目的是创建一组类,使海龟在点击时移动,并且每次返回坐标。这是我到目前为止所拥有的:

import turtle

class point:
    def __init__(self,x=0,y=0):
        """make a point"""
        self.x=x
        self.y=y

    def __str__(self):
        """print a point"""
        return (("({0},{1})").format(self.x,self.y))

    def distance(self,target):
        """compute distance between two points"""
        import math
        return math.sqrt(((self.x-target.x)**2)+((self.y-target.y)**2))

class GTXsubjects():
    def __init__(self):
        self.vec=turtle.Turtle()
        self.wnd=turtle.Screen()

        self.vec.shape("circle")
        self.vec.shapesize(0.2)
        self.vec.pencolor("white")
        self.vec.penup()

        self.wnd.bgcolor("white")

        self.wnd.onclick(self.vec.goto)

class GTXpoint(GTXsubjects,point):
    def __init__(self,x=0,y=0):
        self.x=self.vec.xcor()
        self.y=self.vec.ycor()

    def __str__(self):
        """print a GTXpoint"""
        return (("({0},{1})").format(self.x,self.y))

GTXsubjects()
print(GTXpoint)

我确定我在课堂行为方面缺乏一些理解。感谢您的帮助

标签: pythonclassinheritance

解决方案


您可以使用该super方法继承和更改父类的属性,而无需更改父类。

class Point:    # Start your class names with a capital
  def __init__(self,x, y):
    self.x=x
    self.y=y

  def __str__(self):
    return '{}, {}'.format(self.x, self.y)

class Ten(Point): # Pass parent class through to inherit attributes
    def __init__(self):
      super().__init__(10, 10)

moves_ten = Ten()

print('spaces you have moved (x, y): ', moves_ten)

>>> spaces you have moved (x, y):  10, 10

推荐阅读