Python-类

类的初始化函数 __init__,类似于C++中的构造函数

类的中的变量分为【对象变量】和【类变量】

【对象变量】用self引用,self类似于C++中的this指针,类中除了静态函数之外,所有函数的第一个参数都是self,要显示写出(这一点与C++不同)

【类变量】类似于C++中的静态变量,引用方法是【类名.变量名】

静态函数需要用staticmathod声明

注意,不要使用__del__,它和C++中的析构函数还是有区别的,不稳定,容易出错。

#!/usr/bin/python

class Robot:
    RobotNum=0
    def __init__(self,name):
        self.name = name
        Robot.RobotNum+=1
    def tell(self):
        print 'My name is',self.name,
        if(Robot.RobotNum==1):
            print 'There is 1 robot only'
        else:
            print 'There are',Robot.RobotNum,'robots'
    def Num():
        print Robot.RobotNum
    Num = staticmethod(Num)

robot1 = Robot('caven')
robot1.tell()
robot2 = Robot('jill')
robot2.tell()
robot3 = Robot('grace')
robot3.tell()

 

继承

#!/usr/bin/python

class SchoolMember:
    def __init__(self,pname,page):
        self.name = pname
        self.age = page
    def tell(self):
        print 'name:',self.name,'age:',self.age,

class Teacher(SchoolMember):
    def __init__(self,pname,page,psalary):
        SchoolMember.__init__(self,pname,page)
        self.salary = psalary
    def tell(self):
        SchoolMember.tell(self)
        print 'salary:',self.salary

class Student(SchoolMember):
    def __init__(self,pname,page,pmark):
        SchoolMember.__init__(self,pname,page)
        self.mark = pmark
    def tell(self):
        SchoolMember.tell(self)
        print 'mark:',self.mark


list = [Teacher('Bill',46,'$1000'),Student('John',23,124)]
for member in list:
    member.tell()

output:

name: Bill age: 46 salary: $1000
name: John age: 23 mark: 124

类的继承方法是:在定义子类时,在类名的后面加上要继承的父类名
子类要显示调用父类的初始化函数

posted @ 2014-09-09 12:21  米其林轮船  阅读(119)  评论(0编辑  收藏  举报