Classes & objects · 类与对象
A class is a blueprint
- A class defines a new kind of thing — a user-defined type.
- An object is one item made from that class.
- One
Dogclass can make many dog objects, each with its own data.
类是一张蓝图
- 类(class)定义一种新的事物 —— 一个用户自定义类型。
- 对象(object)是用这个类造出来的一个实例。
- 一个
Dog类可以造出许多狗对象,每个都有自己的数据。
init and attributes
__init__is a special method that runs when you make an object.selfrefers to the object being made.- Values stored on
selfare the object's attributes (its data).
init 与属性
__init__是一个特殊方法,在你创建对象时运行。self指代正在被创建的那个对象。- 存放在
self上的值就是对象的属性(attribute,它的数据)。
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(2, 5)
print(p.x)
print(p.y)
Methods
- A method is a function defined inside a class.
- Its first parameter is always
self, the object it works on. - Call it with a dot:
object.method().
方法
- 方法(method)是定义在类内部的函数。
- 它的第一个参数永远是
self,即它所操作的对象。 - 用点号来调用它:
object.method()。
class Greeter:
def __init__(self, name):
self.name = name
def hello(self):
return "Hi, " + self.name
g = Greeter("Sam")
print(g.hello())
Enumerated types
- An enumerated type is a fixed set of named values.
from enum import Enumlets you define one as a class.- It is clearer than using loose numbers like
1,2,3.
枚举类型
- 枚举类型(enumerated type)是一组固定的、有名字的值。
from enum import Enum让你把它定义成一个类。- 这比使用零散的数字(如
1、2、3)更清晰。
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.GREEN)
print(Color.GREEN.value)
In Cambridge pseudocode
- A
CLASSblock lists its data and aNEWconstructor.
用剑桥伪代码表示
CLASS代码块列出它的数据和一个NEW构造函数。
CLASS Point
PRIVATE X : INTEGER
PRIVATE Y : INTEGER
PUBLIC PROCEDURE NEW(startX : INTEGER, startY : INTEGER)
X ← startX
Y ← startY
ENDPROCEDURE
ENDCLASS
DECLARE p : Point
p ← NEW Point(2, 5)
Common mistakes
- Every method takes
selfas its first parameter. __init__runs automatically when you create an object.
常见错误
- 每个方法的第一个参数都是
self。 - 创建对象时
__init__会自动运行。
Now you try
- Define each class with
__init__and any methods it needs. - Press Check answer to test your code.
现在轮到你
- 给每个类都定义好
__init__以及它需要的方法。 - 按检查答案来测试你的代码。
Define a class Dog whose __init__ takes name and age and stores them as attributes self.name and self.age. · 定义一个类 Dog,它的 __init__ 接收 name 和 age,并把它们存为属性 self.name 和 self.age。
Click Run to see the output here. · 点击“运行”查看此处输出。
Define a class Rectangle with __init__(self, width, height) and a method area(self) that returns · 返回值 width * height. · 定义一个类 Rectangle,有 __init__(self, width, height) 和一个方法 area(self),返回 width * height。
Click Run to see the output here. · 点击“运行”查看此处输出。
Define a class BankAccount. __init__ sets self.balance to · 到 0. Add deposit(self, amount) to add money and withdraw(self, amount) to take it away. · 定义一个类 BankAccount。__init__ 把 self.balance 设为 0。添加 deposit(self, amount) 来存钱,withdraw(self, amount) 来取钱。
Click Run to see the output here. · 点击“运行”查看此处输出。