11 1
10.1 10.2 10.3 10.4 10.5 10.6 * 10.7 2
10.1 3
11.1.1 1. 使 GOTO 使 4
2. 5
1 2 便 3 便 4 5 6
11.1.2 使 使 访 7
10.2 8
11.2.1 class ( ): class Person(object): pass class Person(): pass class Person: pass Python 3.x 3 9
Person class Person: name = 'Holly' # def printName(self): # print(self.name) 10
11.2.2 使 = ( ) 访 . . ( ) 11
11-1 Employee Employee 访 class Employee: empCount = 0 # def __init__(self, name, salary): # self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): # print("Total Employee %d" % Employee.empCount) def displayEmployee(self): # print("Name : ", self.name, ", Salary: ", self.salary) 12
# Employee emp1 = Employee("Zara", 2000) # Employee emp2 = Employee("Manni", 5000) emp1.displayEmployee() emp2.displayEmployee() print("Total Employee %d" % Employee.empCount) Name : Zara , Salary: 2000 Name : Manni , Salary: 5000 Total Employee 2 13
10.3 14
访 15
11.3.1 1. __init__() self. = name sex height 178 16
11-2 Student ID name sex st1 st2 class Student: def __init__(self, ID, name, sex): self.ID = ID self.name = name self.sex = sex def sayhello(self): fmt = "Hello, " if self.sex == "female": fmt = fmt + "Ms. {}!" else: fmt = fmt + "Mr. {}!" print(fmt.format(self.name)) 17
st1 = Student("1111","Holly","female") # st1.sayhello() st2 = Student("2222","John","male") # st2.sayhello() print(st1.name, " ", st1.ID) Hello, Ms. Holly! Hello, Mr. John! Holly 1111 . self. 18
2. . . 使 19
11-3 Team company boss ID leader t1 t2 class Team: company = "ABC" boss = "Jenny" def __init__(self, ID, leader): self.ID = ID self.leader = leader 20
t1 = Team("1", "Holly") # t2 = Team("2", "John") # print(" :{}\n :{}".format(Team.company, Team.boss)) print("{} {}".format(t1.ID, t1.leader)) print("{} {}".format(t2.ID, t2.leader)) :ABC :Jenny 1 Holly 2 John 21
11.3.2 Python 线 线 线 访 线 线 22
class Parent: # def __init__(self, value): self.__value = value class Child(Parent): # Parent def get_value(self): return self.__value child = Child(4) print(child.get_value()) 23
11.3.3 线 特殊属性或方法名 含义与作用 object.__dict__ 字典,除了一些特殊的属性,实例、类型等对象的所 有属性,都放置在其 __dict__ 字典中。 instance.__class__ 类实例所属的类,可理解为当前实例的模板。 class.__bases__ 类对象的基类构成的元组,只包含直接基类,并不是 继承链上的所有基类。 definition.__name__ 对象的名称,比如 type class 对象的名称就是系统 内置的或自定义的名称字符串,类型的实例通常没有 属性 __name__ definition.__qualname__ 类的限定名称。 class.__mro__ 该属性用于存储 MRO 元组,以便在方法解析期间提供 基类排序。该属性是动态的,每当继承层次更新时, 该属性都可能发生改变。 24
1 特殊属性或方法名 含义与作用 class.mro() 通过元类( metaclass )可以覆盖此方法,以自定义 类实例的方法解析顺序。该方法会在程序初始化时 调用,其结果存储在 __mro__ 中。 class.__subclasses__() 返回子类列表。 __init__() __init__() 是一个实例方法,用来在实例创建完成 后进行必要的初始化,该方法必须返回 None Python 不会自动调用父类的 __init__() 方法,需要 额外的调用 super(C, self).__init__() 来完成。 __new__(cls[, args...]) __new__() 是一个静态方法,用于根据类型创建实例 Python 在调用 __new__() 方法获得实例后,会调用 这个实例的 __init__() 方法,然后将最初传给 __new__() 方法的参数都传给 __init__() 方法。 25
2 特殊属性或方法名 含义与作用 __del__(self) GC garbage collector )之前, Python 会调用这 个对象的 __del__() 方法完成一些终止化工作。如果 没有 __del__() 方法,那么 Python 不做特殊的处理。 __repr__(self) __repr__() 方法返回的字符串主要是面向解释器的 ,如果没有定义 __repr__() ,那么 Python 使用一种 默认的表现形式。 __str__(self) __repr__() 返回的详尽的、准确的、无歧义的对 象描述字符串不同, __str__() 方法只是返回一个对 象的简洁的字符串表达形式;当 __str__() 缺失时, Python 会调用 __repr__() 方法。 __unicode__(self) 优先级高于 __str__() 方法;同时定义这两个方法的 实例,调用结果则相同。 26
10.4 27
3 28
11.4.1 def (self, [ ]): . 1 self 29
11-4 class Person(object): def __init__(self, name, score): self.__name = name self.__score = score def get_grade(self): if self.__score >= 80: return 'A' if self.__score >= 60: return 'B' return 'C' p1 = Person('Bob', 90) p2 = Person('Alice', 65) p3 = Person('Tim', 48) print(p1.get_grade()) print(p2.get_grade()) print(p3.get_grade()) 30
1 self self 使 31
11.4.2 @classmethod def (cls, [ ]): 1 cls . . 32
11-5 class Goods: __discount = 1 #   def __init__(self, name, price): # self.name = name self.price = price 33
1 @ classmethod def change_discount(cls, new_discount ): cls.__discount = new_discount   @ property # property 使 def finally_price(self): return self.price * self.__discount 34
2 banana = Goods(' ', 10) apple = Goods(' ', 16)   Goods.change_discount(0.8) print(banana.finally_price) print(apple.finally_price)   Goods.change_discount(0.5) print(banana.finally_price) print(apple.finally_price ) 8.0 12.8 5.0 8.0 35
11.4.3 @staticmethod def ([ ]) 36
11-6 class Game: @staticmethod def menu(): print('------') print(' [1]') print(' [2]') print(' 退 [3]') Game.menu() . . 37
10.5 38
11.5.1 使 class ( 1 [, 2, ...]) 39
11-7 Person Man class Person: # def __init__(self, name, age): # self.name = name self.age = age def print_age(self): # print("%s's age is %s" % (self.name, self.age)) 40
1 class Man(Person): # work = "Teacher" def print_age(self): # print("Mr. %s's age is %s" %(self.name, self.age)) def print_work(self): # print("Mr. %s's work is %s" %(self.name, self.work)) Man 41
2 bob = Man('Bob', 33) bob.print_age() bob.print_work() Mr. Bob's age is 33 Mr. Bob's work is Teacher 42
11.5.2 Python len() ...... 43
11-8 Circle Square Rectangle Area() import math class Circle: def __init__(self, r): self.r = r def Area(self): # area = math.pi * self.r ** 2 return area 44
1 class Square: def __init__(self, size): self.size = size def Area(self): # area = self.size * self.size return area 45
2 class Rectangle: def __init__(self, a, b): self.a = a self.b = b def Area(self): # area = self.a * self.b return area 46
3 a = Circle(5) print(a.Area()) b = Square(5) print(b.Area()) c = Rectangle(2, 3) print(c.Area()) 78.53981633974483 25 6 47
10.6 * 48
OOP C++ Java “+” Python Python 49
Python is and or not Python 50
1 类型 运算符 特殊方法 含义 一元运算符 - __neg__ 负号 + __pos__ 正号 ~ __invert__ 对整数按位取反 51
2 类型 运算符 特殊方法 含义 中缀运算符 + __add__ 加法 - __sub__ 减法 * __mul__ 乘法 / __truediv__ 除法 // __floordiv__ 整除 % __mod__ 取模(求余) ** __pow__ 幂运算 52
3 类型 运算符 特殊方法 含义 复合赋值算术运 算符 += __iadd__ 加法 -= __isub__ 减法 *= __imul__ 乘法 /= __itruediv__ 除法 //= __ifloordiv__ 整除 %= __imod__ 取模(求余) **= __ipow__ 幂运算 53
4 类型 运算符 特殊方法 含义 比较运算符 < __lt__ 小于 <= __le__ 小于等于 > __gt__ 大于 >= __ge__ 大于等于 == __eq__ 等于 != __ne__ 不等于 54
5 类型 运算符 特殊方法 含义 位运算符 & __and__ 位与 | __or__ 位或 ^ __xor__ 位异或 << __lshift__ 左移 >> __rshift__ 右移 55
6 类型 运算符 特殊方法 含义 复合赋值位运 算符 &= __iand__ 位与 |= __ior__ 位或 ^= __ixor__ 位异或 <<= __ilshift__ 左移 >>= __irshift__ 右移 56
11-9 + class MyNumber: def __init__(self, value): self.data = value # data def __repr__(self): # str(), return "Mynumber(%d)" % self.data def __add__(self, other): v = self.data + other.data r = MyNumber(v) return r 57
n1 = MyNumber(100) n2 = MyNumber(200) n3 = n1 + n2 # print(n3.data) print(n1, '+', n2, '=', n3) 300 Mynumber(100) + Mynumber(200) = Mynumber(300) 58
10.7 59
11-10 Dog name color weight bark “wang Wang class Dog: # def __init__(self, name, color, weight): # self.name = name self.color = color self.weight = weight def bark(): # print("wang! wang!") Dog.bark() # 60
11-11 Rectangle class Rectangle: def __init__(self, left, top, right, bottom): # self.left = left self.top = top self.right = right self.bottom = bottom 61
def get_area(self): # a = self.right - self.left b = self.bottom - self.top return abs(a * b) rec = Rectangle(0, 1, 5, 8) print("Area=", rec.get_area()) Area= 35 62
11-12 绿 class Color: # def __init__(self, red, green, blue): # self.red = red self.green = green self.blue = blue 63
1 def show_color(self): # color_str = "(" + str(self.red) + "," + str(self.green) + "," + str(self.blue) + ")" print(color_str) def modi_red(self, red): # self.red = red 64
2 class Rainbow(Color): # def __init__(self, red, green, blue, orange, yellow, cyan, purple): self.red = red self.green = green self.blue = blue self.orange = orange self.yellow = yellow self.cyan = cyan self.purple = purple 65
3 def show_color(self): # color_str = "(" + str(self.red) + "," + str(self.green) + "," + str(self.blue) + "," color_str = color_str + str(self.orange) + "," + str(self.yellow) + "," color_str = color_str + str(self.cyan) + "," + str(self.purple) + ")" print(color_str) def modi_purple(self, purple): # self.purple = purple 66
4 if __name__ == '__main__': # c1 = Color(150, 230, 100) # Color print("Before:c1=", end="") c1.show_color() c1.modi_red(200) print("After:c1=", end="") c1.show_color() c2 = Rainbow(100, 200, 50, 30, 60, 80, 150) print("Before:c2=", end="") c2.show_color() c2.modi_red(200) c2.modi_purple(0) print("After:c2=", end="") c2.show_color() Before:c1=(150,230,100) After:c1=(200,230,100) Before:c2=(100,200,50,30,60,80,150) After:c2=(200,200,50,30,60,80,0) 67
11-13 1 2 3 4 5 68
class Member: # count = 0 # def __init__(self, name, sex, age, department): self.name = name self.sex = sex self.age = age self.department 69
1 class Teacher(Member): # count=0 # def __init__(self, name, sex, age, department, title, course): self.name = name self.sex = sex self.age = age self.department = department self.title = title self.course = course Teacher.count += 1 Member.count += 1 def __del__(self): # Teacher.count -= 1 Member.count -= 1 70
2 class Student(Member): # count = 0 # def __init__(self, name, sex, age, department, major, time_enrollment): self.name = name self.sex = sex self.age = age self.department = department self.major = major self.time_enrollment = time_enrollment Student.count += 1 Member.count += 1 def __del__(self): # Student.count -= 1 Member.count -= 1 71
3 class Staff(Member): # count = 0 # def __init__(self, name, sex, age, department, salary): # self.name = name self.sex = sex self.age = age self.department = department self.salary = salary Staff.count += 1 Member.count += 1 def __del__(self): # Staff.count -= 1 Member.count -= 1 72
4 t1 = Teacher("Holly", "female", 30, "Computer", "Professor", "Network") t2 = Teacher("John", "male", 40, "Computer", "Lecture", "OS") t3 = Teacher("Jenny", "female", 50, "Maths", "Professor", "Matrix") stu1 = Student("Ada", "female",20, "Computer", "Network Engineering", "Sept 1,2018") stu2 = Student("Jorge", "male", 21, "Computer", "Network Engineering", "Sept 1,2017") stf1 = Staff("Rose", "famale", 35, "Maths", 3500) print("Before:") print(" :", Teacher.count) print(" :", Student.count) print(" :", Staff.count) 73
5 del t1 del stu1 del stf1 print("After:") print(" :", Teacher.count) print(" :", Student.count) print(" :", Staff.count) Before: : 3 : 2 : 1 After: : 2 : 1 : 0 74
档铺网——在线文档免费处理