python笔记:2.1.4.5多重继承

面向对象编程实践
本文介绍了一个基于面向对象编程的人类类实现,通过继承和方法覆盖展示了多态性,同时介绍了如何使用类方法和实例方法来操作类信息。
# -*- coding: utf-8 -*-
"""
Created on Tue May 14 11:01:33 2019

@author: User
"""

class Human(object):
    
    domain = 'eukarya'
    def __init__(self, kingdom='Animalia',phylum='Chordata',
                order='Primates',family='Human Being'):
        self.kingdom = kingdom
        self.phylum=phylum
        self.__order = order
        self.family = family
    
    def typewrite(self):
        print('This is %s typing words!' %self.family)
    def add(self, n1, n2):
        n = n1 + n2
        print(str(n1) + '+' + str(n2) + '+' + str(n))
        print('You see! %s can calculate!' %self.family)
        
    @classmethod
    def showclassmethodinfo(cls):
        print(cls.__name__) #__name__属性,其值为类名
        print(dir(cls))    #使用dir列示本类的所有方法

        
class Male(Human):
    def __init__(self,gender='male'):
        super(Male,self).__init__() #
        self.gender=gender
    def less(self, n1, n2):
        '''为子类增加一个名为less的方法'''
        n = n1 - n2
        print(str(n1) + '-' + str(n2) + '=' + str(n))
        print('你看,%s 可以计算!' %self.gender)
    def add(self, n1, n2):
        '''为子类重新定义add方法'''
        n = n1 - n2
        print(str(n1) + '-' + str(n2) + '=' + str(n))
        print('你看,%s 不能使用加法计算!' %self.gender)
    def showclassmethodinfo(self):
        print("这是 Male 的class method 信息:")
        super(Male,self).showclassmethodinfo()
        print("\n这是 Male 的 instance method 信息:")
        print(dir(self))
        
class Female(Human):
    def __init__(self,gender='female'):
        super(Female,self).__init__() #
        self.gender=gender
    def add(self, n1, n2):
        '''为子类重新定义add方法'''
        n = n1 - n2
        print(str(n1) + '-' + str(n2) + '=' + str(n))
        print('你看,%s 不能使用加法计算!' %self.gender)
    def div(self, n1, n2):
        n = n1 / n2
        print(str(n1) + '/' + str(n2) + '=' + str(n))
        print('你看,%s 能使用除法计算!' %self.gender)       

class Somebody(Male, Female):
    pass

print(list(filter(lambda x:x[0] != '_', dir(Somebody()))))

运行:

['add', 'div', 'domain', 'family', 'gender', 'kingdom', 'less', 'phylum', 'showclassmethodinfo', 'typewrite']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值