一:继承:基类和派生类
区分“属于”(is-a)和“具有”(has-a)这两种关系。“属于”即为继承:在这种关系中,派生类的一个对象也属于“基类”的一个对象。
“具有”即为“合成”:这种关系中,一个对象“具有”对其他类的一个或多个对象的引用,后者是前者的成员。
基类即超类,派生类即子类
创建派生类的格式:
class Paishenclassname(Jileiclassname):
...
#class 派生类名(基类名):
....
#即:表示Paishenclass 类 继承了 Jileiclass的所有属性、方法
下面的例子,
补充知识:
issubclass(A,B),判断A类是否是B类的子类;
isinstance(a,A),判断a是否是A类的对象;
A.__bases__,返回A类的基类,如果没有基类,返回
举例:关于圆是点的子类;
import math
class Point:
'''Class that represents geometric point'''
def __init__(self,xValue=0,yValue=0):
'''Point constructor take x and y coordinates'''
self.x=xValue
self.y=yValue
class Circle(Point):
'''Class that represents a circle'''
def __init__(self,x=0,y=0,radiusValue=0.0):
'''Circle corstructor takes x and y coordinates of center
point and radius'''
Point.__init__(self,x,y)#class base-class constructor
self.radius=float(radiusValue)
def area(self):
'''Computes area of a Circle'''
return math.pi * self.radius ** 2
#main program
#examine classes Point and Circle
print("Point bases:",Point.__bases__)
print("Circle bases:",Circle.__bases__)
print("Point is a subclass of Circle:",issubclass(Point,Circle))
print("Circle is a subclass of Point:",issubclass(Circle,Point))
point =Point(30,50)#create Point object
circle=Circle(120,89,2.7)#create Circle object
print("\ncircle is a Circle object:",isinstance(circle,Point))
print("point is a Circle object:",isinstance(point,Circle))
print("Circle is a point object:",isinstance(circle,Point))
#print Point and Circle objects
print ("\npoint members:\n\t",point.__dict__)
print("circle menbers:\n\t",circle.__dict__)
print("\nArea of circle:",circle.area())
运行结果:
Point bases: (,)
Circle bases: (,)
Point is a subclass of Circle: False
Circle is a subclass of Point: True
circle is a Circle object: True
point is a Circle object: False
Circle is a point object: True
point members:
{'x': 30, 'y': 50}
circle menbers:
{'x': 120, 'y': 89, 'radius': 2.7}
Area of circle: 22.902210444669596