本章我们看看Python关于类的定义、创建实例、类变量、实例变量的一些知识
一、类
# -*- coding: gb18030 -*-
# 1、类的定义
class Person:
#初始化函数,相当于C++中的构造函数
def __init__(self,str="Hello"):
self.contents = str
#定义实例方法,每个实例方法均有一个self参数,来传递当前实例,相当于C++中的this
def say(self):
print "say:%s" %(self.contents)
#只定义方法,无方法体,用pass代替
def speak(self):
pass
#相当于C++中的析构函数
def __del__(self):
print '---------'
#实例化,并传递参数
p = Person("China")
#调用实例方法
p.say()
输出结果:
二、类的继承
#2、类的继承
class Teacher(Person):
def __init__(self,str,salary=2300):
#继承父类的__init__方法,并定义自己的实例变量salary
Person.__init__(self, str)
self.salary = salary
#定义自己的实例方法
def get_salary(self):
print "say:%s" %(self.contents)
print "salary:%s" %(self.salary)
#定义子类对象,并传递参数
t = Teacher("China",1230)
t.get_salary()
t.say()
输出结果:
三、类变量、实例变量
# -*- coding: gb18030 -*-
#类变量,实例变量
class Person:
def __init__(self,str="Hello"):
self.contents = str
def say(self):
print "say:%s" %(self.contents)
class Persion:
population = 0 #类变量,只有一份拷贝
def __init__(self, name):
self.name = 111 #self.name 表示实例变量
print '(Initializing %s)' % self.name
#When this person is created, he/she adds to the population
Persion.population += 1 #访问类变量,将改变其值
def __del__(self):
print '%s says bye.' % self.name
Persion.population -= 1
if Persion.population == 0:
print 'I am the last one.'
else:
print 'There are still %d people left.' % Person.population
def sayHi(self):
print 'Hi, my name is %s.' % self.name
def howMany(self):
if Persion.population == 1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' % Person.population
swaroop = Persion('Swaroop')
swaroop.sayHi()
swaroop.howMany()
输出结果: