python的语法基础之类的特性
一、类的继承
例:
1 import random as r 2 class Fish(): 3 def __init__(self): 4 self.x=r.randint(0,10) 5 self.y=r.randint(0, 10) 6 def move(self): 7 print("现在的位置是:" ,self.x,self.y) 8 class Goldfish(Fish): 9 pass 10 class Shark(Fish): 11 def __init__(self): 12 super().__init__() 13 self.hungry=True 14 def eat(self): 15 if self.hungry: 16 print("我在吃东西,肚子好饿") 17 self.hungry=False 18 else: 19 print("好饱,吃不下了,呜呜") 20 fish=Fish() 21 fish.move() 22 goldfish=Goldfish() 23 goldfish.move() 24 shark=Shark() 25 shark.move() 26 shark.eat() 27 shark.eat()
二、类的多重继承
例:
class Base1: def Fun1(self): print("我是Fun1,我是Base1的方法") class Base2: def Fun2(self): print("我是Fun2,我是Base2的方法") class User(Base1,Base2): pass client=User() client.Fun1() client.Fun2()
三、类的组合
例:
class Fish: def __init__(self,x): self.num=x class Wugui: def __init__(self, x): self.num = x class Pool: def __init__(self,x,y): self.wugui=Wugui(x) self.fish=Fish(y) def print_num(self): print("水池里面一共有乌龟%d 只,小鱼%d 条 " % (self.wugui.num,self.fish.num)) pool=Pool(1,3) pool.print_num()