范例,前面加__就设置成为private类型了self.__age = age
#coding:utf-8
class Student:
'''学生类'''
#类的属性(C++:静态成员变量)
school = "myschool"
def __init__(self, name, age):
'''构造函数'''
print "__init__()..."
#对象的属性(C++:普通的成员属性)
self.name = name
self.age = age
#(C++:普通成员方法) 在python中 对象的方法
def showMe(self):
print "__showme is called..."
print self.name
print self.age
print Student.school
#c++中静态方法和普通方法最大的区别 静态方法没有this指针,不能访问对象成员
#python中类的方法
@classmethod
def getSchool(cls):
#print self.name
return cls.school
#析构
def __del__(self):
print "__del___"
if __name__ == "__main__":
print "************"
s1 = Student("aaa", 18)
s1.showMe()
s1.age = 100
s1.showMe()
print "************"
Student.school = "hust"
s2 = Student("akali", 20)
s2.showMe()
print "************"
print Student.getSchool()
输出:
__init__()...
__showme is called...
aaa
18
hust
__init()__
__showme is called...
akali
20
hust
***********
school
__del__
__del__