1 ##类的使用方法 2 ##实例1: 3 class Dog(object): 4 typee="宠物" #类变量 5 #初始化方法 6 def __init__(self,a,b,c): 7 self.name = a #实例变量 8 self.age = b 9 self.color = c 10 def eat(self): #普通方法 11 print(self.name,"在啃骨头!") 12 def run(self,speed): 13 print(self.name,"在飞快的跑!速度:",speed) 14 #实例化对象 15 dog=Dog("小黑",3,"白色") 16 print(dog.name) 17 dog.eat() 18 dog.run("3m/s") 19 输出: 小黑 小黑 在啃骨头! 小黑 在飞快的跑!速度: 3m/s 20 21 ##实例2:(类的私有属性) 22 class Card(object): 23 def __init__(self, num,pwd,ban): 24 self.num = num 25 self.pwd = pwd 26 self.__ban = ban #余额 私有属性(只能在类的内部被访问) 27 28 def cun(self): 29 print("存款!") 30 def getBan(self,numm,pwdd): 31 if numm==self.num and pwdd==self.pwd: 32 return self.__ban 33 else: return "输入错误!" 34 35 #实例化对象 36 card=Card("1001","123456",10000) print(card.getBan("1001","123456")) 37 print(card._Card__ban) 38 输出: 1000 1000 39 40 ##实例3: 41 class Animal(object): 42 def __init__(self, color): 43 self.color = color 44 def eat(self): 45 print("动物再吃") 46 def run(self): 47 print("动物再跑") 48 49 class Cat(Animal): 50 def eat(self): 51 print("猫在吃鱼") 52 class Dog(Animal): #Dog继承Animal类 53 def __init__(self, name,age,color): 54 super(Dog, self).__init__(color) #调用父类的初始化方法 55 self.name = name 56 self.age = age 57 def eat(self): 58 print("狗在啃骨头!") 59 60 dog=Dog("小黑",10,"黑色") 61 dog.eat() 62 print(dog.color) 63 64 ##实例3:多态 65 def feed(Obj): 66 Obj.eat() an=Animal("黄") 67 cat=Cat("橘色") 68 69 dog=Dog("小黑",2,"黑色") 70 feed(dog) 71 feed(cat) 72 输出: 狗在啃骨头! 黑色 狗在啃骨头! 猫在吃鱼
---------------------
作者:S-gavin
源地址:https://www.cnblogs.com/zwh-Seeking/p/11525592.html
来源:博客园cnblogs© 转载请附上博文链接哦!谢谢!