• python面向对象编程基础



           演示了 Python 类与对象的编程基础, 包括属性、方法、继承、组合、动态创建类。 python 版本: 2.7.5

           

    class SimpleClass(object):
    
        '''  a simple demo for python class  '''        
    
        commonResource = 1000
    
        def __init__(self, name, age):
            print 'object has built: ', str(self)
            self.name = name
            self.age = age
            SimpleClass.decrease()
    
        def info(self):
            return 'id is: %d, my name is %s, and age is %d' % (SimpleClass.commonResource, self.name , self.age)
    
        @classmethod
        def decrease(cls):
            SimpleClass.commonResource-=1
    
        @classmethod
        def getCommonResource(cls):
            return SimpleClass.commonResource
        
    
    class Person(SimpleClass):
        
        ''' Person definition '''
        
        def __init__(self, name, age, sex, __secret):
            super(Person, self).__init__(name, age)
            self.sex = sex
            self.__secret = __secret
    
        def info(self):
            return super(Person, self).info() + 
                ', i am a ' + ('girl' if self.sex == 'female' else 'boy') + '.' + 
                '
    my secret: ' + self.__secret
                 
    
    class CanFly(object):
    
        skill = 'I can fly !'
        def fly(self, info=None):
            return (info if info else ' ') + CanFly.skill 
    
    
    class CanSwim(object):
    
        skill = 'I can swim !'
        def swim(self, info=None):
            return (info if info else ' ') + CanSwim.skill 
    
            
    # static multiple inheritance
    class CanDoManyThing(CanFly, CanSwim):
        pass
                
    class PersonCanFlyAndSwim(Person, CanDoManyThing):
        pass
    
    
    # combination
    class PersonCanDoManyThing(object):
    
        def __init__(self, person, skills):
            self.person = person
            self.skills = skills
    
        def showSkills(self):
            print self.person.info() + self.skills.fly() + self.skills.swim()
    
        def updateSkills(self, newSkills):
            self.skills = newSkills
    
        def showDySkills(self):
            infostr = self.person.info()
            subclasses = self.skills.__class__.__bases__
            for subclass in subclasses:
                infostr += subclass().skillIn()
            print infostr
    
    if __name__ == '__main__':
    
        cat = SimpleClass('mimi', 2)
        print '<' + cat.name + ',' + str(cat.age) + '>'
        # no private instance attribute in python class
        
        print SimpleClass.getCommonResource()
        cat.decrease()
        print SimpleClass.commonResource
        # no private class attribute in python class  
    
        print '
    ----------- my lover --------------'
    
        mylover =  PersonCanFlyAndSwim('yanni', 26, 'female', 'OO')
        print mylover.fly(mylover.info())
    
        print '
    ----------- me --------------'
    
        me = Person('qinshu', 30, 'male', 'Oh')
        mecando = PersonCanDoManyThing(me, CanDoManyThing())
        mecando.showSkills()
    
        class SkillTpl(object):
            def skillIn(self):
                return 'I can ' + self.skill + ' !'
            
        def dyGenSkillClass(skillName):
            SkillClass = type(skillName, (SkillTpl,), {'skill': skillName})
            
            return SkillClass
    
        skillNameList = ['Reading', 'Writing', 'Riding']
        skillClasses = []
        for skillName in skillNameList:
            SkillClass = dyGenSkillClass(skillName)
            skillClasses.append(SkillClass)
        
        t = tuple(skillClasses)
        DynamicSkills = type('MySkills', t, {})
        myskillsNow = DynamicSkills()
        mecando.updateSkills(myskillsNow)
        mecando.showDySkills()
    
        print '
    ----------- other ----------------'
    
        print "class name: %s
    class doc: %s
    module: %s" % 
            (SimpleClass.__name__ , SimpleClass.__doc__, SimpleClass.__module__)
        print "class attr: ", dir(SimpleClass)
    
        print mylover.__dict__
        print dir(mylover)
    
        # private instance attribute name in python class should start with __
        try: 
            print me.__secret
        except AttributeError, arg:
            print arg
            
    
    
  • 相关阅读:
    win10安装nodejs,修改全局依赖位置和环境变量配置
    JavaScript判断两个对象内容是否相等
    JS判断是否是数组
    Js判断值是否是NaN
    typeof方法重写(区分数组对象)
    JS实现图片懒加载
    输入url到展示页面过程发生了什么?
    html如何在服务端跑起来
    nuxt怎么打包
    如果scss引用了字体图标文件该怎么打包
  • 原文地址:https://www.cnblogs.com/lovesqcc/p/4037666.html
Copyright © 2020-2023  润新知