Classes & objects
Python for A-Level CS Lesson 10 2:38 English narration · English + 中文 subtitles burned in
Chapters
Transcript
A class defines a new kind of thing — a type you invent yourself.
类定义了一种新的东西——一个你自己发明的类型。
This one says a point has an x and a y, and that is all it says: it holds no numbers, because it is the shape, not the thing.
这个类说:一个点有一个 x 和一个 y,而它说的就只有这些: 它本身不装任何数字,因为它是"形状",不是那个东西。
From it you stamp out objects.
从它你可以造出对象。
Here are two, p and q, and the point of the picture is that each carries its own copy of the data.
这里有两个,p 和 q, 而这张图的重点是:每一个都带着自己的一份数据。
Changing p's x cannot touch q.
改动 p 的 x,碰不到 q。
Init is the method that fills a new object in, and you never call it by name: it runs automatically the moment you write Point of two, five.
init 是负责把一个新对象填好的方法,而你从不按名字调用它: 当你写下 Point(2, 5) 的那一刻,它就自动运行了。
Its first parameter, self, is the object being made.
它的第一个参数 self,就是正在被创建的那个对象。
So self dot x equals x means the value that came in is stored on the object, and when init finishes, p exists with its own x and its own y.
所以 self.x = x 的意思是:传进来的值被存到了这个对象上, 而当 init 结束时,p 就存在了,带着它自己的 x 和自己的 y。
A method is just a function written inside the class, and it also takes self first.
方法就是写在类里面的一个函数,它同样以 self 作为第一个参数。
You call it with a dot — g dot hello, with empty brackets.
你用一个点来调用它——g.hello(),括号是空的。
Those brackets look empty, but they are not: the dot hands the object in as self.
那对括号看起来是空的,其实不是: 那个点把对象作为 self 传了进去。
That is the whole trick, and it is why the method can read g's own name and answer Hi, Sam.
整个窍门就在这里, 这也是为什么这个方法能读到 g 自己的 name,并回答 "Hi, Sam"。
One more thing the syllabus asks for.
考纲还要求一样东西。
Storing a state as a bare two is legal and unreadable — six months later nobody knows what two meant.
把一个状态存成一个光秃秃的 2 是合法的,也是读不懂的—— 六个月以后没人知道那个 2 是什么意思。
An enumerated type is a fixed set of values that carry a name instead.
枚举类型是一组固定的值,它们带着名字。
In Python it is defined as a class that inherits from Enum, and each member still has a number underneath if you need it.
在 Python 里,它被定义成一个继承自 Enum 的类, 而如果你需要,每个成员底下仍然有一个数字。
And here is the same class in the exam's notation, line for line.
这里是同一个类在考卷写法下的样子,一行对一行。
CLASS opens it, ENDCLASS closes it, and the procedure called NEW is the exam's constructor — it is init under a different name.
CLASS 开始,ENDCLASS 结束, 而那个叫 NEW 的过程就是考卷的构造器——它就是换了个名字的 init。
PRIVATE on the two data items means only the class's own methods may touch them, which is the idea lesson eleven calls encapsulation.
两个数据项前面的 PRIVATE 表示只有这个类自己的方法可以碰它们, 这个概念第 11 课称之为"封装"。
Four things to take with you.
带走四点。
One: a class is a blueprint; an object is one item made from it.
第一:类是蓝图;对象是由它造出的一个具体的东西。
Two: init runs when you create the object.
第二:init 在你创建对象时运行。
Three: every method takes self as its first parameter.
第三:每一个方法都以 self 作为第一个参数。
Four: self dot name equals value stores data on that object.
第四:self.name = value 把数据存到那个对象上。
Now do the three tasks.
现在去做那三道题。