python - 乌龟的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)
我确定我在课堂行为方面缺乏一些理解。感谢您的帮助
解决方案
您可以使用该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
推荐阅读
- java - 使用 Java 将 PySpark 提交到 Yarn 集群
- android - 如果 JSONArray 中的 id 相同,如何在一个 textview 上显示值
- android - Flutter 中的卡片轮播
- symfony - Symfony Query Builder:避免转义双引号
- firebase - 我在 Firestore 中有数据,并提交了值,但其中一些显示为 null
- java - 无法生成 DataBindingClass(Impl 确实生成)
- google-cloud-platform - gcloud 函数部署失败,出现 .cloudignore 文件
- r - 如何在 R 的 tidyverse 中有效地嵌套()和 unnest_wider()
- r - 在 rmarkdown 的代码块中插入幻灯片中断
- mysql - “我已经准备好了mysql调用过程/函数。但是在调用过程/函数时错误来了。”