#!/usr/bin/env python # _*_ coding:utf-8 _*_ class Role(object): #继承object类 ac = None #脚本一执行跟着类一起存到了内存 类变量 #类变量和实例变量的区别: #类变量脚本执行跟着类一起存到了内存,不管是否调用都存在,实例变量是存在实例内的, def __init__(self,name,role,weapon): #初始化方法 实例化后自动执行 #self 代表实例本身.谁调用就是谁。 name role,weapon真正实例化后存在P1 t1没有实例化前调用不到 ac是存在类里的 self.name = name #实例变量 self.role = role self.weapon = weapon def buy_weapon(self,weapon): print(‘%s is buying [%s]‘ %(self.name,weapon)) self.weapon = weapon # p1 = Role("SB",‘Police‘,‘AK47‘) #P1 实例 Role 类 self代表实例本身 把一个抽象的类变成一个具体的对象的过程叫实例化 p2 = Role("38",‘Thief‘,‘B51‘) p1.buy_weapon(‘B10‘) #==Role.buy_weapon(p1,‘AK10‘) p2.buy_weapon(‘B11‘) print("P1",p1.weapon) print("P2",p2.weapon)
继承
#!/usr/bin/env python # _*_ coding:utf-8 _*_ class SchoolMember(object): def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex self.enroll() #只要一实例化就自动调用 enroll方法 def enroll(self): print("SchoolMember [%s] is enrolled!" %self.name) def tell(self): print("My name is [%s]" %self.name) class Teacher(SchoolMember): def __init__(self,name,age,sex,course,salary): #不写__init__ 就是继承了父类SchoolMember的init。先重写父类的init namne/age/sex在继承 super(Teacher,self).__init__(name,age,sex) #super继承。上面重写了父类的name age sex super再继承回来 #另一种写法 SchoolMember.__init__(self,name,age,sex) 旧式写法 经典类和新式类的区别 self.course = course self.salary = salary def teaching(self): print(‘Teacher [%s] is teaching [%s] ‘ %(self.name,self.course)) class Student(SchoolMember): def __init__(self,name,age,sex,course,tuition): super(Student, self).__init__(name,age,sex) self.course = course self.tuition = tuition def pay_tuition(self): print("cao, stutent [%s] paying tuition [%s]" %(self.name,self.tuition)) t1 = Teacher("SB",22,‘F‘,‘PY‘,1000) t2 = Teacher("DSB",23,‘F‘,‘PY‘,2000) s1 = Student(‘JB‘,11,‘F‘,‘PY‘,9000) s2 = Student(‘DJB‘,12,‘F‘,‘PY‘,8000) #print(s2.name) t1.teaching() t1.tell() s1.pay_tuition() s1.tell()
#!/usr/bin/env python # _*_ coding:utf-8 _*_ #多态 class Animal: def __init__(self, name): # Constructor of the class self.name = name def talk(self): # Abstract method, defined by convention only raise NotImplementedError("Subclass must implement abstract method") class Cat(Animal): def talk(self): return ‘Meow!‘ class Dog(Animal): def talk(self): return ‘Woof! Woof!‘ animals = [Cat(‘Missy‘), Dog(‘Lassie‘)] ‘‘‘ 用函数方式实现,不用上面的列表实现 def animal_talk(obj): print(obj.talk()) c = Cat("miaomi") d = Dog("wangwang") animal_talk(c) animal_talk(d) ‘‘‘ for animal in animals: print (animal.name + ‘: ‘ + animal.talk()) #多态实现接口的统一化,统一调用animal 无需关心里面的dog和cat #面向对象继承封装多态的总结:封装可以隐藏实现的细节,使得代码模块化;继承可以扩展已存在的代码模块(类);他们的目的都是为了-----代码重用。 #而多态则是为了实现另一个目的----接口重用!多态的作用就是为了类在继承和派生的时候,保证使用“家谱”中任一类的实例的某一属性时的正确调用
时间: 2024-10-18 05:21:54