class Ball: #创建个类,注意这里类中只有方法,没有属性。 def bounce(self): if self.direction == "down": self.direction ="up" myBall = Ball() #创建个对象
myBall.direction ="down" #在申请好对象后可以随意定属性!
myBall.color ="red"
myBall.size = "small"
print ("I just created a ball.")
print ("My ball is ", myBall.size)
print ("My ball is",myBall.color)
print ("My ball's direction is",myBall.direction)
print ("Now I'm going to bounce the ball")
myBall.bounce()
print ("Now the ball's direction is",myBall.direction)
这里申明了类似于构造函数
class Ball: def __init__(self,color,size,direction): self.color = color self.size =size self.direction = direction
def bounce (self):
if self.direction == "down":
self.direction = "up"
myBall = Ball("red","small","down")
print ("I just created a ball.")
print ("My ball is",myBall.size)
print ("My ball is ",myBall.color)
print ("Now I'm going to bounce the ball")
myBall.bounce()
print ("Now the ball's direction is",myBall.direction)