【发布时间】:2017-11-04 13:31:21
【问题描述】:
我有以下创建形状类的代码,我有两个问题希望得到解答: 1.运行以下代码时,输出为:
>>>
100
100
None
>>>
最后的“无”是什么,我怎样才能摆脱这个输出?
2。理想情况下,我希望能够(在输出屏幕中)绘制一个正方形。我不想使用 pygame。我确实想知道是否可以集成turtle来做到这一点,但不知道如何开始?对于使用海龟执行此操作的方法有什么建议,或者任何其他天才建议?
from turtle import*
class Shape:
#self is how we refer to things in the clas from within itself. .self is the first parameter in any function defined inside a class
#to access functions and variables inside the class, their name must be preceded with self and a full-stop (e.g. self.variable_name)
def __init__(self,x,y):
self.x=x #the shape has the attribute x (width)
self.y=y #the shape has the attribute y (height)
description="The shape has not yet been brought into being"
author="No one has yet claimed authorship of this shape"
def area(self):
return self.x*self.y
def perimeter(self):
return 2*self.x+2*self.y
def describe(self,text):
self.description =text
def authorName(self,text):
self.author=text
def scaleSize(self,scale):
self.x=self.x*scale
self.y=self.y*scale
def print(self):
print(self.x)
print(self.y)
square=Shape(100,100)
print(square.print())
我可能会补充一点,关于 SO 有一个类似的问题,但没有具体或有用的答案
Using class to draw shapes in turtle
更新:
我尝试了类似的方法,但无法正常工作。我想我需要在构造函数的某个地方初始化 turtle - 但是在哪里以及如何
from turtle import*
class Shape:
#self is how we refer to things in the clas from within itself. .self is the first parameter in any function defined inside a class
#to access functions and variables inside the class, their name must be preceded with self and a full-stop (e.g. self.variable_name)
def __init__(self,x,y):
self.x=x #the shape has the attribute x (width)
self.y=y #the shape has the attribute y (height)
description="The shape has not yet been brought into being"
author="No one has yet claimed authorship of this shape"
def area(self):
return self.x*self.y
def perimeter(self):
return 2*self.x+2*self.y
def describe(self,text):
self.description =text
def authorName(self,text):
self.author=text
def scaleSize(self,scale):
self.x=self.x*scale
self.y=self.y*scale
def print(self,shapename):
print("This shape is a", shapename, "with dimensions:>",self.x,"by",self.y)
def draw(self):
turtle.forward(self.x)
turtle.left(90)
turtle.forward(se.f.x)
turtle.left(90)
turtle.forward(self.y)
turtle.left(90)
turtle.forward(self.y)
turtle.left(90)
square=Shape(100,100)
square.print("square")
print("The perimeter is:",square.perimeter())
print(square.draw())
【问题讨论】:
-
print(square.print())此行在控制台上生成 None ,因为函数没有返回任何内容。要删除它,只需删除外部 print() 并保持剩余。即square.print() -
谢谢!关于第二个问题的任何想法!
-
我在上面:) 我会在某个时候更新
-
谢谢!添加了更新。 (绘制的代码不正确)但这就是想法。我不知道从哪里让类认龟......
-
警告,通过
from turtle import *和class Shape:你正在重新定义海龟自己的Shape类!您可以通过在您的class Shape:(重新)定义之前和之后打印id(Shape)来确认这一点。您应该限制您的导入,import turtle或from turtle import Turtle, Screen,或者将您的Shape类重命名为其他名称。