内建函数issunclass和isinstance,可用来判断一个类是否派生自另一个类,并判断一个值是特定类的一个对象,函数那个类的一个子类。
类和继承 import math #class Point class Point: def __init__(self, xValue, yValue): self.X = xValue self.Y = yValue #class Circle class Circle(Point): def __init__(self, xValue, yValue, rValue): Point.__init__(self, xValue, yValue) self.Radious = rValue def area(self): return math.pi * self.Radious ** 2 #driver print("Point bases:", Point.__bases__) print("Circle bases:", Circle.__bases__) print("Circle is the subclass of Point:", issubclass(Circle, Point)) print("Point is the subclass of Circle:", issubclass(Point, Circle)) point = Point(3, 4) circle = Circle(4, 5, 2) print("point is an instace of Point:", isinstance(point, Point)) print("circle is an instace of Point:", isinstance(circle, Point)) print("point members:", point.__dict__) print("circle members:", circle.__dict__) print("the area if circle is:", circle.area())
设计原则:抽象类不应该拥有构造函数
引起的原因:
一个公共抽象类型拥有一个公共的构造函数
描述:
构造函数被用来建立一个对象实例,但是你不能建立一个抽象类型的实例,抽象类型的构造函数就仅仅能够被它的继承类型使用。因此,为一个抽象类构造公共构造函数是一个错误的设计。
修复:
如果需要修复这个问题,可以声明这个构造函数为保护型,或者,声明这个类型不是一个抽象类型。
一个类需不需要构造函数要看具体情况,和是不是抽象类(虚基类)没有关系。
一个类格构造函数的作用是对其成员进行初始化,抽象类也有可能包含需要初始化的成员,也需要进行初始化。
初始化可以在基类的构造函数中进行,也可以在派生类的构造函数中进行。如果没有定义构造函数,编译器会自动生成缺省的复制型构造函数。我个人的看法是,不管在什么情况下都应该尽量抛开编译器的因素,自己编写构造函数。
造函数没有必要写成虚函数,编译器会自动调用父类的构造函数。而析构函数则不同,一般应该写成虚函数。
Python中也有多态性和抽象类的概念 Python2.2以后,类和类型变成一个概念了 #覆盖父类的同名方法 #class Employee class Employee: def __init__(self, firstName, lastName): self.firstName = firstName self.lastName = lastName def __str__(self): return "%s %s" % (self.firstName, self.lastName) #class HourlyWorker class HourlyWorker(Employee): def __init__(self, firstName, lastName, initHours, initWages): Employee.__init__(self, firstName, lastName) self.initHours = float(initHours) self.initWages = float(initWages) def __str__(self): return "%s is an hourly worker with pay of %.2f" % / (Employee.__str__(self), self.getPay()) def getPay(self): return self.initHours * self.initWages #main program hourlyworker = HourlyWorker("wang", "yang", 7.5, 20) print("Calling __str__ setval ways: ") print(hourlyworker) #隐式调用 print(hourlyworker.__str__()) #显式调用 print(HourlyWorker.__str__(hourlyworker)) #显式未绑定调用
Python中的静态方法和静态成员
使用内建方法staticmethod创建静态方法
#Pthon中静态方法和静态成员示例 class Employee: '''static method and static member''' numberOfEmployees = 0 maxEmployees = 10 def isCrowded(): '''static method ''' return Employee.numberOfEmployees > Employee.maxEmployees #create static method isCrowded = staticmethod(isCrowded) def __init__(self, firstName, lastName): self.first = firstName self.last = lastName Employee.numberOfEmployees += 1 def __del__(self): '''Employee destructor''' Employee.numberOfEmployees -= 1 def __str__(self): return "%s %s" % (self.first, self.last) #main program def main(): answers = ["NO", "YES"] employeeList = [] #class static method using class print("Employees are isCrowed?") print(answers[Employee.isCrowded()]) print("creat 11 objects of class Employee") for i in range(11): employeeList.append(Employee("John", "Terry" + str(i))) print("Employees are isCrowed?") print(answers[Employee.isCrowded()]) print("Remove one Employee..") del employeeList[0] print("Employees are isCrowed?/n", answers[Employee.isCrowded()]) if __name__ == "__main__": main()
__slots__类属性,可以用来限定只允许类的对象拥有的属性
__slots__用来规定对象的属性
#Simple class with slots class PointWithoutSlots: def __init__(self, xValue=0.0, yValue=0.0): self.x = float(xValue) self.y = float(yValue) class PointWithSlots: __slots__ = ["x", "y"] def __init__(self, xValue=0.0, yValue=0.0): self.x = float(xValue) self.y = float(yValue) #main program def main(): noSlots = PointWithoutSlots() Slots = PointWithSlots() for point in [noSlots, Slots]: print("/n Processing an object of class", point.__class__) print("The current value of point.x is %d" % (point.x)) newValue = float(input("Enter new x Value:")) print("Atemping to set new x Vlaue...") point.X = newValue print("the new value of point.x is%d" % (point.x)) if __name__ == "__main__": main()
Pytho中属性的概念。
通过函数property()来创建属性,这样就可以访问类的私有成员
#property()属性的使用
class Point: def __init__(self, xValue, yValue): '''私有属性,不能在外面访问''' self.__x = xValue self.__y = yValue def setX(self, xValue): self.__x = xValue def getX(self): return self.__x x = property(getX, setX, "x") def setY(self, yValue): self.__y = yValue def getY(self): return self.__y y = property(getY, setY, "y") point = Point(3, 5) print(point.x) point.x = 4 print(point.x) print(point.y) point.y = 7 print(point.y)
第10章 GUI编程
1、Label组件的示例
#Lable 组件的演示 from tkinter import * class LabelDemo(Frame): '''Demonstrate Labels''' def __init__(self): '''Create thress Labels and pack them''' Frame.__init__(self) #initializes Frame Object #frame fills all available space self.pack(expand = YES, fill = BOTH) self.master.title("Label") self.Label1 = Label(self, text = "Label with text") #resize frame to accomamodate Label self.Label1.pack() self.Label2 = Label(self, text = "Label with text and a bitmap") #insert Label against left side of frame self.Label2.pack(side = LEFT) #using default bitmap image as label self.Label3 = Label(self, bitmap = "warning") self.Label3.pack(side = LEFT) def main(): LabelDemo().mainloop() #starts event loop if __name__ == "__main__": main()
第12章 异常的处理
#Simple exception handling example number1 = input("Enter number: ") number2 = input("Enter denominator: ") try: number1 = float(number1) number2 = float(number2) result = number1 / number2 except ValueError: print("You must enter two numbers") except ZeroDivisionError: print("Attempted to divide by zero") else: print("%.3f / %.3f = %.3f" % (number1, number2, result))
异常的栈反解
#Demonstraing exception arguments and stack unwinding import traceback def function1(): function2() def function2(): function3() def function3(): try: raise Exception("An exception has occurred") except Exception: print("Caught exception in function3. Reraiseing.../n") raise try: function1() except Exception: print("Exception caught in main program") print("/nException arguments:", Exception.args) print("/nException message:", Exception) print("/nTraceback:") traceback.print_exc()
自定义异常类
import math class NegativeNumberError(ArithmeticError): pass def squareRoot(number): if number < 0: raise (NegativeNumberError, "Square root of negative number") return math.sqrt(number) while 1: try: userValue = float(input("Please input a number: ")) print(squareRoot(userValue)) except ValueError: print("The enterd value is not a number") except NegativeNumberError as exception: print("catch") print(exception) else: break
1、Python提供ord函数,它取得一个字符做参数,并返回该字符的字符代码(ASCII码)。 2、Python中字符串是一个基本数据类型。字符串的是一种“不可变序列”,创建后就不能改变。 3、字符串的格式化 (1)、字符串的对齐 str = "wangyang" print(str.center(50)) print(str.ljust(50)) print(str.rjust(50)) (2)、删除空格 str = "/twangyang/t" print(str) print(str.strip()) print(str.lstrip()) print(str.rstrip()) 4、搜索字符串 string1 = "Test1, test2, test3, test4, Test5, test6" print("/"test/" occurs %d times in %s/n" % (string1.count("test"), string1)) print("/"test/" occurs %d times after 18th character in %s/n" %(string1.count("test", 18, len(string1)), string1)) str = "Odd or even" print("%s contains /"or/" starting at index %d" % (str, str.find("or"))) #find index of "even" try: print("/"even/" index is %d" % (str.index("even"))) except ValueError: print("/"even/" does not occur in %s" % (str)) if str.startswith("Odd"): print("%s starts with /"Odd/"" % (str)) 5、连接和分解字符串 split()和join() string = "A, B, C, D, E" print(string.split(",")) print(string.split(" ")) print(string.split(",", 2)) list1 = ["A", "B", "C", "D", "E"] str = "_+_" print(str.join(list1))
1、读取文件 import sys #wirte the file try: file = open("wy.txt", "w") except IOError as message: print(std.error, "File could not be opened", message) sys.exit(1) print("Enter the account , name and balance.") print("Enter quit to end input.") while 1: try: accountLine = input("? ") except EOFError: break else: if accountLine == "quit": break file.write(accountLine+"/n") file.close() #read file try: file = open("wy.txt", "r") except IOError as message: print(std.error, "File could not be opened", message) sys.exit(1) readline = file.readlines() for line in readline: print(line) 读取文件的第2种方式 import sys #read file try: file = open("wy.txt", "r") except IOError: print("can not open the file") sys.exit(1) for line in file: //读取文件行 print(line) 2、shelve文件 3、对象的序列化 Python用pickle和cPickle模块来执行序列化。 cPickle模块的执行效率要高于pickle模块,因为cPickle是用C语言实现的。