接着定义了继承Person的student类:
class Student(Person):
def __init__(self,
name = None,
age = 1,
sex = "men",
grade = 0):
Person.__init__(self, name, age, sex)
self.grade = grade
def displayInfo(self):
Person.displayInfo(self)
print "grade : %-20d" % self.grade
Student类中的 init 方法中调用了父类的 init 方法,同时加了一条打印 给grade属性赋值的语句。Student类中重定义了父类displayInfo方法,它的 内部也调用了父类的displayInfo方法。
在C++语言中有私有方法的概念,私有方法只能被类的内部方法调 用。在Python 中,类的私有方法和私有属性,不能够从类的外面调用。类 的方法和属性是公有,还是私有,可以从它的名字判断。如果名字是以两 个下划线开始,但并不是以两个下划线结束,则是私有的。其余的都是公 有的。请看下面的例子:
import math
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __str__(self):
return ’(’ + str(self.x) + ’,’ + str(self.y) + ’)’
class Line:
def __init__(self, p1 = Point(), p2 = Point()):
self.__p1 = p1 #私有属性
self.__p2 = p2
def __str__(self):
return str(self.__p1) + str(self.__p2)
def __distance(self): #私有方法
tx = math.pow(self.__p1.x, 2) + math.pow(self.__p2.x, 2)
ty = math.pow(self.__p1.y, 2) + math.pow(self.__p2.y, 2)
return math.sqrt(tx + ty)
def length(self):
print self.__distance()
在这个例子中,Line类的两个属性p1和p2是私有的属性,而方法 distance是 私有方法。如果试图用如下的语句调用他们,将显示错误信息:
>>> Line().__p1
AttributeError: Line instance has no attribute ’__p1’
>>> Line().__distance
AttributeError: Line instance has no attribute ’__distance’
错误信息显示在类Line中没有与之对应的属性。这表明私有的方法和属性 不能在类的的外部调用。
上一篇:《Python学习笔记》第十四章
下一篇:Python自然语言分析