python类继承实例教程
内建函数issunclass和isinstance,可用来判断一个类是否派生自另一个类,并判断一个值是特定类的一个对象,函数那个类的一个子类。
1,python类和继承
复制代码 代码示例:
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())
设计原则:抽象类不应该拥有构造函数
引起的原因:
一个公共抽象类型拥有一个公共的构造函数
描述:
构造函数被用来建立一个对象实例,但是你不能建立一个抽象类型的实例,抽象类型的构造函数就仅仅能够被它的继承类型使用。因此,为一个抽象类构造公共构造函数是一个错误的设计。
修复:
如果需要修复这个问题,可以声明这个构造函数为保护型,或者,声明这个类型不是一个抽象类型。
一个类需不需要构造函数要看具体情况,和是不是抽象类(虚基类)没有关系。
一个类格构造函数的作用是对其成员进行初始化,抽象类也有可能包含需要初始化的成员,也需要进行初始化。(脚本学堂 www.jb200.com 收集整理)
初始化可以在基类的构造函数中进行,也可以在派生类的构造函数中进行。如果没有定义构造函数,编译器会自动生成缺省的复制型构造函数。我个人的看法是,不管在什么情况下都应该尽量抛开编译器的因素,自己编写构造函数。
造函数没有必要写成虚函数,编译器会自动调用父类的构造函数。而析构函数则不同,一般应该写成虚函数。
二,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)