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') + '.' + \
            '\nmy 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 '\n----------- my lover --------------'

    mylover =  PersonCanFlyAndSwim('yanni', 26, 'female', 'OO')
    print mylover.fly(mylover.info())

    print '\n----------- 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 '\n----------- other ----------------'

    print "class name: %s\nclass doc: %s\nmodule: %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
        

 


posted @ 2014-09-19 19:34  琴水玉  阅读(276)  评论(0编辑  收藏  举报