类,实例/对象方法

时间:2017-01-29 22:59:00

标签: python class object

我是编程新手。我对这个类/实例/方法定义非常困惑。

我有一个简单的问题。

如果我在一张纸上用红笔画一个正方形,有人可以在这里解释什么是类,方法和对象吗?

此外,这是一个真实程序的代码。基于上面的解释,我怎样才能开始类似地思考Python?

import turtle

def draw_square():
      window = turtle.Screen() #canvas to draw on
      window.bgcolor("red")

      brad = turtle.Turtle()
      brad.shape("triangle")
      brad.speed('10000')
      brad.forward(100)
      brad.right(90)
      brad.forward(100)
      brad.right(90)
      brad.forward(100)
      brad.right(90)
      brad.forward(100)




      window.exitonclick()


 draw_square()  

1 个答案:

答案 0 :(得分:1)

在你的类比中,这个类将是“Square”,因为它是一个抽象的概念,代表某种东西的类型(在这种情况下,你在纸上绘制的东西的类型)。 “绘制”将是方法,因为它是对对象执行的操作。对象将是您绘制的特定方块。因此,如果您将两个相同的正方形彼此相邻,则会有两个对象,它们都具有相同的类。

我已对您的代码进行了评论,以便对其进行解释:

import turtle

def draw_square():  # We are defining a method
      window = turtle.Screen() # window is an object.  Its class is turtle.Screen
      window.bgcolor("red") # We are calling the bgcolor() method, which sets the color

      brad = turtle.Turtle() # We are creating an object called brad, whose class is turtle.Turtle
      brad.shape("triangle") # We are calling a method on brad, called shape
      brad.speed('10000')    # We are calling a method on brad, called speed
      brad.forward(100)      # We are calling a method on brad, called forward
      brad.right(90)         # etc. etc.
      brad.forward(100)
      brad.right(90)
      brad.forward(100)
      brad.right(90)
      brad.forward(100)




      window.exitonclick()    # We are calling a method on window, called exitonclick


 draw_square()  # We are calling a method called draw_square, which we defined above