🐸

机器人的诞生

Python 基础python-architect-18-the-birth
奖励: 100 XP
|

如果每座房子看起来都一模一样,那蓝图就没什么用了。我们需要定制化!

当一个机器人诞生(被创建)时,我们需要立即给它一个独特的名字和涂装。

__init__ 咒语

这是一个特殊的咒语(方法),它会在对象被创建的那一刻 自动 运行。 它决定了“建造配置”。

class Cat:
  def __init__(self, name):
      self.name = name

# "name" 被传递给了 __init__
kitty = Cat("Luna") 
print(kitty.name) # Luna
1
定义 __init__

Robot 内部,定义 def __init__(self, name, color):

2
存储数据

__init__ 内部,保存这些值:self.name = nameself.color = colorself 的意思是“我现在正在建造的这一个具体的机器人”。

3
建造定制机器人

使用 Robot("R2", "Blue") 创建 bot1,并给 bot2 起一个不同的名字/颜色。

它的拼写是 __init__,两边各有两个下划线!它是 "initialize"(初始化)的缩写。

参考答案
点击展开
参考答案:
class Robot:
  def __init__(self, name, color):
      self.name = name
      self.color = color

# 建造 R2-D2
bot1 = Robot("R2", "Blue")

# 建造 C-3PO
bot2 = Robot("C3", "Gold") 

# 打印它们的详细信息
print("Bot 1: " + bot1.name + " (" + bot1.color + ")")
print("Bot 2: " + bot2.name + " (" + bot2.color + ")")
高级技巧
想更进一步?点击展开

F. 属性 (Attributes)

  • 在对象内部的变量(像 self.nameself.color)被称为 属性
  • 每个对象都有它自己的一组属性。修改 bot1.name 不会影响 bot2.name。它们是独立的个体!
Loading...
终端输出
Terminal
Ready to run...