[:StartProgramming: (首页)开始编程之旅] 翻译自Lee Harr的[http://staff.easthighschool.net/lee/computers/book/Start_Programming.html Start Programming] 本文是使用[http://www.nongnu.org/pygsear/ pygsear]+[http://pygame.org pygame]作为开发环境,以初级用户角度来分步分阶段学习[http://www.python.org PYTHON]基本概念,并以小游戏开发项目为具体案例,介绍的十分详细。编写风格清新朴实,没有象一般教科书那样枯燥,极其适合初级用户来激发兴趣时使用。
1. StartProgramming-2-5 Classes
classes can also be loaded from modules.
A class defines a type of object.
Penguin, for example, is a class in the penguin module which we have already used extensively. To make a new instance of a Penguin, we first import the class, and then call it:
attachment:box_class_penguin.png
A class is sort of like a function which acts as a factory for creating objects. Each time you call the class, it returns an object of that class.
1.1. class Ball
Classes define data and methods which describe the different objects you want to use in your programs.
Let's start out with a very basic object, a ball.
Put that code in to a file. Call it Ball.py
To create a ball, simply call your new class:
Keep in mind that this is all very abstract at this point, and this code is not going to show you a picture of a ball. This is just the idea of a ball. It is more beautiful, really, if you think about it.
If you really need to see a ball right now, here is a red one I made with the GIMP:
attachment:ball_red.png
1.2. reload
Notice that we did not import your new class directly. It is import Ball and not from Ball import Ball. This makes it easier to change your module and see the changes.
If you want to make a change to your class -- like if you made a typing error -- you can just do this:
1.3. color
The Ball class defines two methods: set_color() and bounce()
Methods are like functions, but they are bound to particular objects.
Once you create a ball, you can change its color:
1 rb.set_color('bright red')
Notice that with methods, unlike with functions, you do not pass in the first parameter (usually called self). The object itself is passed in automatically as the first parameter when the method is called from a class instance.
Also notice the difference between color and self.color in the set_color() method.
When you call rb.set_color('red') the variable self is bound to the same Ball instance that rb is bound to.
At the same time, the variable color is bound to the string 'red'.
Then with the code self.color = color the data attribute self.color is bound to that same string.
The set_color() method will create the attribute self.color if it does not exist, or if self.color already exists, it will just set it to the new value.
You can see what color the ball is by examining the attribute:
1 rb.color
1.4. get and set
It is a good idea to access data attributes through "getter" and "setter" methods, so we should create a get_color() method which just returns self.color
Using methods to access your object attributes allows you to keep the interfaces to the attributes the same, even if later the underlying implementation changes.
In other words, set_color() might have side effects other than just setting self.color -- it might check first to make sure that you do not try to set the color to orange, or you might decide later that the color would actually be better stored in a different way.
1.5. bounce
The other method in this class so far is bounce(). You can make the ball bounce by calling that method:
attachment:boing_boing.png
All bounce() does is print a message to the console.
Using print statements like this can be a simple way to debug your class methods. You can print out various values at different times and see if they match up to what you think they should be.
Often you will get an error message or a weird value from the print, and you can start your investigation there.
1.6. __init__
One problem with the Ball class the way we have the code now is that if you try to check the color before you set it, you will get an error:
To make sure that the Ball always has a color, we should include the special method init() to initialize the objects to a known state when they are created.
Adding init(), the class will now look like this:
The init() method is called automatically when you instantiate your class, and it can take parameters like any other function.
Remember that any time you make changes to your module you will need to either re-start the interpreter or else reload() the module.
will create a ball with its color set to the default 'white', and
1 yb = Ball.Ball('yellow')
will make a 'yellow' ball.
1.7. Inheritance
The real power of classes emerges when you understand inheritance.
Inheritance means that a class can define a new object which is a type of another object.
For example, we might create a new object SuperBall which is a type of Ball:
1.8. Add, Override, Extend
If SuperBall defined no methods at all, it would be just like Ball. What we want, though, is something that is like a Ball, but with some changes.
One thing we can do is add completely new methods.
The superbounce() method adds a capability which a normal Ball just does not have.
If your class defines a method which is also in its parent class, the new method will be called instead of the parent class method -- the new method overrides the parent method. In this case, The bounce() method is one which both Ball and SuperBall have.
Calling bounce() on a SuperBall overrides the normal Ball.bounce(). In this case, it prints out a message, and then calls the superbounce() method too.
Sometimes what you want is the parent class's behavior, plus something more.
The SuperBall.init() method starts out by calling Ball.init() to get the normal Ball initialization.
This is a common idiom in subclasses, and you should probably do it just like this until you have a better understanding of how classes and inheritance work.
Notice that since Ball.init() is called against the class Ball and not against an instance of class Ball you need to explicitly pass in the Ball instance (self) as the first parameter.
After that, SuperBall.init() also prints out an informative message. At this point, it could also set up any additional attributes which a SuperBall has, but which a Ball does not.