python 创建类的语法
class Cat: def __init__(self, new_name): self.name = new_name def eat(self): print("%s爱吃鱼" % self.name) tom = Cat("tom") tom.eat() tom2 = Cat("tom2") tom2.eat()
class Person: def __init__(self, name, weight): self.name = name self.weight = weight def __str__(self): return '我的名字叫 %s 体重 %.2f ' % (self.name, self.weight) def run(self): print("跑步锻炼身体") self.weight -= 0.5 def eat(self): print("吃东西容易长胖") self.weight += 1 ming = Person("小明", 75.0) ming.run() ming.eat() print(ming)
一个对象的 属性 也可以是 另外一个类创建的对象
class Gun: def __init__(self, model): # 枪的型号 self.model = model # 子弹数量 self.bullet_count = 0 def add_bullet(self, count): self.bullet_count += count def shoot(self): # 判断是否还有子弹 if self.bullet_count <= 0: print("没有子弹了...") return # 发射一颗子弹 self.bullet_count -= 1 print("%s 发射子弹[%d]..." % (self.model, self.bullet_count))
class Soldier: def __init__(self, name): # 姓名 self.name = name # 枪,士兵初始没有枪 None 关键字表示什么都没有 self.gun = None def fire(self): # 1. 判断士兵是否有枪 if self.gun is None: print("[%s] 还没有枪..." % self.name) return # 2. 高喊口号 print("冲啊...[%s]" % self.name) # 3. 让枪装填子弹 self.gun.add_bullet(50) # 4. 让枪发射子弹 self.gun.shoot()
# 创建枪对象 ak47 = Gun("ak47") # 创建士兵对象 xusanduo = Soldier("许三多") xusanduo.gun = ak47 xusanduo.fire()

浙公网安备 33010602011771号