代码书写原则:
1)不能重复写代码
2)写的代码要经常变更
编程模式概述
- 面向过程:根据业务逻辑从上到下写垒代码
- 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可
- 面向对象:对函数进行分类和封装,让开发“更快更好更强...”
面向对象编程
面向对象的三大特性:封装、继承和多态
一、封装
class Role(object): 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): print("%s is buying [%s]" %(self.name,weapon)) self.weapon = weapon #role 的实例 #把一个抽象的类变成一个具体对象的过程叫实例化 p1 = Role('Alan','Police','B10',100) t1 = Role('Petter','Terrorist','B11',100) p1.buy_weapon("AK47") #Role.bur_weapon(p1,"AK47") t1.buy_weapon("B51") print("P1:",p1.weapon) print("T1:",t1.weapon)
二、继承
class SchoolMember(object): def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex 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): super(Teacher,self).__init__(name,age,sex) 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("Student [%s] paying tuition [%s]" %(self.name,self.tuition)) t1 = Teacher("John", 30, "Male", "C", 10000) t2 = Teacher("Jonna", 25, "Female", "UI",15000) s1 = Student("Jeff", 27, "Male", "PY", 10000) s2 = Student("Alice", 28, "Male", "Java", 12000)
三、多态
多态性(polymorphisn)是允许你将父对象设置成为和一个或更多的他的子对象相等的技术,赋值之后,父对象就可以根据当前赋值给它的子对象的特性以不同的方式运作。简单的说,就是一句话:允许将子类类型的指针赋值给父类类型的指针。
那么,多态的作用是什么呢?我们知道,封装可以隐藏实现细节,使得代码模块化;继承可以扩展已存在的代码模块(类);它们的目的都是为了——代码重用。而多态则是为了实现另一个目的——接口重用!多态的作用,就是为了类在继承和派生的时候,保证使用“家谱”中任一类的实例的某一属性时的正确调用。
python本身不支持多态,以下是python模拟的多态:
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!' def animal_talk(obj): print(obj.talk()) c = Cat("Cat") d = Dog("Dog") animal_talk(c) animal_talk(d) ''' animals = [Cat('Missy'), Dog('Lassie')] for animal in animals: print (animal.name + ': ' + animal.talk()) '''