1. 程式人生 > >python:類與基類簡介(一)

python:類與基類簡介(一)

 

 

一:繼承:基類和派生類

區分“屬於”(is-a)和“具有”(has-a)這兩種關係。“屬於”即為繼承:在這種關係中,派生類的一個物件也屬於“基類”的一個物件。

“具有”即為“合成”:這種關係中,一個物件“具有”對其他類的一個或多個物件的引用,後者是前者的成員。

基類即超類,派生類即子類

建立派生類的格式:

class Paishenclassname(Jileiclassname):
    ...

#class  派生類名(基類名):
    ....
#即:表示Paishenclass  類   繼承了  Jileiclass的所有屬性、方法

下面的例子,

補充知識:

issubclass(A,B),判斷A類是否是B類的子類;

isinstance(a,A),判斷a是否是A類的物件;

A.__bases__,返回A類的基類,如果沒有基類,返回<class'object'>

舉例:關於圓是點的子類;

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: (<class 'object'>,)
Circle bases: (<class '__main__.Point'>,)
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