四、Python:类

 

 本章我们看看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()

 

输出结果:


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值