python 类定义 继承

Posted .Think

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 类定义 继承相关的知识,希望对你有一定的参考价值。

1 定义一个时间类,带默认参数

class mytime(object):
    def __init__(self,hour=21,                  minute=13,                  second=50):
        self.hour   = hour
        self.minute = minute
        self.second = second
        
    def __str__(self):
        return __str__ hour:minute:second = %02d:%02d:%02d                %(self.hour,self.minute,self.second)
    
    def get_hour(self):
        return self.hour
    
    def get_minute(self):
        return self.minute
    
    def get_second(self):
        return self.second

    def print_time(self):
        print  hour:minute:second = %02d:%02d:%02d %(self.hour,self.minute,self.second)
  

说明:  构造函数     __init__(self,hour=21, minute=13, second=50)  带默认参数的定义方式 ;

     用于输出的函数    __str__

           得到某属性值的方法    get_xxxx

           输出属性值的方法 print_time

2 定义日期时间类,继承时间类的属性和方法

class mydatetime(mytime):
    def __init__(self,year = 2016,mounth = 1,day = 1,                       hour=21, minute=13,second=50):
        super(mydatetime,self).__init__(hour,minute,second)
        self.year = year
        self.mounth = mounth
        self.day = day
        
    def __str__(self):
        return ‘__str__ year--mounth--day = %02d--%02d--%02d‘                %(self.year,self.mounth,self.day)
    
    def __del__(self):
        """ __del__ mydatetime destroyed """
        print "__del__ mydatetime destroyed"
    
    def print_date(self):
        print  ‘year-mounth-day = %04d-%02d-%02d‘         %(self.year,self.mounth,self.day)
#        self.print_time()  

 说明:   mydatetime 继承 mytime 的属性值,这里mydatetime(子类),mytime(父类)

    构造函数     __init__(self,year = 2016,mounth = 1,day = 1, hour=21, minute=13,second=50)  带默认参数的定义方式 ,注意要通过 super初始化父类属性值;

    用于输出的函数    __str__

        输出属性值的方法 print_date

3 测试

if __name__ == ‘__main__‘:

    print "\n"
    print "--"*10," mytime t0:"   
    t0 = mytime()
    print t0
    t0.print_time()
    print t0.get_hour()
    
    print "\n"
    print "--"*10," mytime t1:"     
    t1 = mytime(hour=7,second=20)
    t1.print_time()
    
    print "\n"
    print "--"*10," mydatetime da:"   
    da = mydatetime(minute=40)
    print da
#    da.print_date()
    da.print_time()
    del da

测试输出

>>> runfile(‘F:/Python/hysrc_py/untitled0_class.py‘, wdir=r‘F:/Python/hysrc_py‘)


--------------------  mytime t0:
__str__ hour:minute:second = 21:13:50
hour:minute:second = 21:13:50
21


--------------------  mytime t1:
hour:minute:second = 07:13:20


--------------------  mydatetime da:
__str__ year--mounth--day = 2016--01--01
hour:minute:second = 21:40:50
__del__ mydatetime destroyed
>>> 

 

以上是关于python 类定义 继承的主要内容,如果未能解决你的问题,请参考以下文章

java 代码片段

PYTHON3中 类的继承

python继承简介

Python基础 类继承

python-继承与重用

python基础 继承