简单的python类
Python是一门面向对象的语言,同样有类的概念。类包含成员变量、静态变量、构造函数、析构函数、成员函数,静态函数等。所有变量和函数都要加限定符:成员变量需要加self引用,静态变量则要加self或者类名引用,且在所有类方法的外部定义。同时有权限的概念,保证封装的特性,以及继承的概念。在函数或变量名前面加上两个下划线前缀,将变为私有的属性,外部不可引用。如name -> __name 和 toString -> __toString。注意下面的成员都是公有的,也就是外面可以访问。
这里建一个名为oop.py的Python文件:
#this is a python class
#notice all the members and functions are public, add __ before the member or function name and it will become private
class Province:
#this is a static member of the whole class
staticMember = 1
#constructor function
def __init__(self, name, capital, leader):
self.name = name
self.capital = capital
self.leader = leader
#deconstructor
def __del__(self):
print self.name + ' : deconstructor executing...'
#member function, must has the self as the argument
def toString(self):
print 'name : ' + self.name + '; capital : ' + self.capital + '; leader : ' + self.leader
#use the annotation to label the static method
@staticmethod
def sports_meet():
print 'every province can have sport meeting!'
#instance
sd = Province('ShangDong', 'JiNan', 'ZhangSan')
hb = Province('HeiBei', 'ShiJiaZhuang', 'LiSi')
#call the member function
sd.toString()
hb.toString()
#print the static member by class which can be accessed
print Province.staticMember
#call the static member method by class
Province.sports_meet()
运行命令:
python oop.py
结果:
name : ShangDong; capital : JiNan; leader : ZhangSan
name : HeiBei; capital : ShiJiaZhuang; leader : LiSi
1
every province can have sport meeting!
HeiBei : deconstructor executing...
ShangDong : deconstructor executing...