面向对象与面向过程最主要还是思想上的差异。
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: wanghuafeng #封装:将客观的事物封装成抽象的类,对信息进行隐藏。 #继承:使用现有类的所有功能,在无需编写原有类的情况下对这些功能进行扩展。从一般到特殊。 #多态:允许将子类类型赋值给分类类型的指针。 #object:顶级父类 #class:只要该脚本执行就存放到内存中, class Role(object): #定义防弹衣,存放到类的对象中,类属性 ac = None #name:局部变量 #__init__:初始化函数或初始化方法 #初始化函数,需要调用时才能执行 #实例化时,存放到实例的内存对象中 def __init__(self, name, role, weapon, life_value): #成员变量,只属于实例 self.name = name self.role = role self.weapon = weapon self.life_value = life_value def buy_weapon(self, weapon): #self.name = p1 print("%s is buying [%s]"%(self.name, weapon)) #p1.weapon self.weapon = weapon print(self.ac) #p1:Role的实例,就抽象的类变成一个具体的对象的过程,即实例化。 p1 = Role('xiaoming', 'Police', 'B10', 90) #Role('xiaoming', 'Police', 'B10', 90) t1 = Role('xiaowang', 'Terrorist', 'B11', 100) t2 = Role('xiaowu', 'Terrorist', 'AK47', 100) t3 = Role('xiaoha', 'Terrorist', 'B51', 100) p1.buy_weapon('AK47')#Role.buy_weapon(p1, 'AK47') t1.buy_weapon('B51') p1.ac = "China Brand" t1.ac = "US Brand" Role.ac = "Canada Brand" #Role的内存对象中,创建weapon = "M2" Role.weapon = "M2" print('P1:', p1.weapon, p1.ac) print('T1', t1.weapon, t1.ac) #T2、T3中的weapon是实例中的weapon,与Role.weapon = "M2"无关 print('T2', t2.weapon, t2.ac) print('T3', t3.weapon, t3.ac) #如果直接执行buy_weapon,只是将buy_weapon存放到类的内存中,实例化时还是需要传递name告知是谁要买枪 Role.buy_weapon
封装对象
#!/usr/bin/env python# -*- coding: utf-8 -*-# Author: wanghuafengclass c1: def __init__(self, name, obj): self.name = name self.obj = objclass c2: def __init__(self, name, age): self.name = name self.age = age def show(self): print(self.name)c2_obj = c2('nn', 20)c1_obj = c1('radar', c2_obj)print(c1_obj.obj.name)print(c1_obj.obj.age)
#!/usr/bin/env python# -*- coding: utf-8 -*-# Author: wanghuafengclass c1: def __init__(self, name, obj): self.name = name self.obj = objclass c2: def __init__(self, name, age): self.name = name self.age = age def show(self): print(self.name)class c3: def __init__(self, a1): self.money = 123 self.aaa = a1c2_obj = c2('nn', 20)#c2_obj是c2类型#name = "nn"#age = 20c1_obj = c1('radar', c2_obj)#c1_obj是c1类型#name = "radar"# obj = c2_objprint(c1_obj.name)print(c1_obj.obj.name)print(c1_obj.obj.age)c3_obj = c3(c1_obj)#c3_obj是c3类型#money = 123# aaa = c1_obj#通过c3执行show方法print(c3_obj.aaa.obj.show())
继承
简单继承
#!/usr/bin/env python# -*- coding: utf-8 -*-# Author: wanghuafengclass F1: #父类,基类 def show(self): print("aaa") def foo(self): print(self.name)class F2(F1): #子类,派生类 def __init__(self, name): self.name = name #自己的方法优先级高于父类中的方法 def show(self): print("show")obj = F2("radar")obj.foo()
#没有公共父类的多继承 #!/usr/bin/env python# -*- coding: utf-8 -*-# Author: wanghuafeng#继承的时候:先找自己的方法,如果有直接执行,如果没有找父类#涉及到self时,找obj,如果自己有方法则执行自己的方法,如果没有找父类,若父类中执行该方法时又调用了自己的方法,则执行自己的方法class S1: def F1(self): self.F2() def F2(self): pass#继承就是将父类搬过来,但是相同的方法自己的优先级高class S2(S1): def F3(self): self.F1() def F2(self): pass# obj = S2()# obj.F3()obj = S1()obj.F1()
具有公共父类的继承
#!/usr/bin/env python# -*- coding: utf-8 -*-# Author: wanghuafengclass C_2: def f2(self): print("C-2")class C_1(C_2): def f2(self): print("C-1")class C0(C_2): def f2(self): print("CO")class C1(C0): def f1(self): print("C1")class C2(C_1): def f2(self): print("C2")#左边的优先级高于右边的优先级,C1优先级高于C2#寻找顺序,从左往右,如果左边还有继承继续找,如果还未找到,再回到右边寻找class C3(C1, C2): def f3(self): print("C3")obj = C3()obj.f2()
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: wanghuafeng class SchoolMemeber(object): members_nums = 0 def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex #只要初始化后就直接注册 self.enrool() #注册 def enrool(self): SchoolMemeber.members_nums += 1 print("The [%s] school memeber [%s] is enrool!" % (self.members_nums, self.name)) def tell(self): print("Hello my name is [%s]" % self.name) class Teacher(SchoolMemeber): #如果不写则默认继承父类,如需扩展则需要重写再继承 def __init__(self, name, age, sex, course, salary): #继承父类中的name,age,sex super(Teacher, self).__init__(name, age, sex) self.course = course self.salary = salary #另一种写法 #SchoolMemeber.__init__(self, name, age, sex) def teaching(self): print("Teacher [%s] is teaching [%s]" %(self.name, self.course)) class Student(SchoolMemeber): def __init__(self, name, age, sex, course, tution): super(Student, self).__init__(name, age, sex) self.course = course self.tution = tution def pay_tution(self): print("Student [%s] paying tution [%s]" %(self.name, self.tution)) t1 = Teacher("Wang", 29, "F", "Python", 10000) t2 = Teacher("Radar", 22, "F", "Python", 9000) s1 = Student("DC", 23, "M", "Java", 30000) s2 = Student("DCITS", 25, "M", "Perl", 36000) t1.tell() t1.teaching() s1.tell() s2.pay_tution()
Pyhon不支持多态并且也用不到多态,多态的概念是应用于Java和C#这一类强类型语言中
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: wanghuafeng 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')] for animal in animals: print(animal.name + ': ' + animal.talk()) 字段、方法、属性规则:1.一般情况自己访问自己的字段;2.普通字段只能使用对象访问;3.静态字段用类访问,万不得已可以使用对象访问。class Province: country = "中国" def __init__(self, name): self.name = "alex" #普通方法,由对象去调用执行(方法属于类) def show(self): print(self.name) #静态方法(去掉self加@staticmethod):可以有一个或多个参数也可以没有参数,由类调用执行 #把不使用对象的方法写成静态方法,相对于函数 @staticmethod def f1(cla, arg1, arg2): print(arg1, arg2) #类方法:至少有一个参数,不用传递参数,调用时自动将类名传递 #属于静态方法的一种特殊形式,由类调用执行 @classmethod #cls:类名 #cls():创建对象 #在单例模式时使用 def f2(cls): print(cls) def f3(self): return self.name[1] Province.f1(Province, 11, 22)Province.f2()obj = Province('alex')obj.f3()class Pager: def __init__(self, all_count): self.all_count = all_count #属性 @property def all_pager(self): a1, a2 = divmod(self.all_count, 10) if a2 == 0: return a1 else: return a1 + 1 #设置 @all_pager.setter def all_pager(self, value): print(value) #删除 @all_pager.deleter def all_pager(self): print("del all_pager") p = pager(108)#一般调用时:#p.all_count #字段#result = p.all_pager() #方法#print(result)#使用属性后:ret = p.all_pagerprint(ret)#设置值p.all_pager = 123#删除del p.all_pager 静态字段在代码加载时已经创建;普通字段需要在对象创建时,才能使用对象去访问。对象是来封装数据的。方法:所有的方法属于类1.普通方法:至少一个self,对象执行2.静态方法:任意参数,由类执行3.类方法:至少一个参数cls,由类执行属性不伦不类,具有方法的写作形式,具有字段的访问形式类成员及成员装饰class Foo: def __init__(self, name): self.__name = name