python类的使用3

#!/usr/bin/python
#-*- coding:utf8 -*-

#将将Init函数中弗雷的初始化
class Student(object):
    def __init__(self, name):
        print "student name is: ",name

class SmallStudent(Student):
    def __init__(self, name):
        Student.__init__(self, name)   #一种方法
        #super(SmallStudent, self).__init__(name)  #注意一定要继承object
        #super().__init__(name)   #我电脑上面这个不行,不知到为什么?
        print "small student name is: ",name
        
smallStu = SmallStudent("Jack")


#进行模式选择

class Fruit:
    def __init__(self, color=""):
        self.color = color

class Apple(Fruit):
    def __init__(self, color="red"):
        Fruit.__init__(self, color)

class Pear(Fruit):
    def __init__(self, color="yellow"):
        Fruit.__init__(self, color)

class FruitSelect:
    def selFruit(self, fruit):
        if isinstance(fruit, Apple):
            print "Your select is Apple"
        elif isinstance(fruit, Pear):
            print "Your select is Pear"
        else:
            print "Your select is others"

App = Apple("bigred")
fruSel = FruitSelect()
fruSel.selFruit(App)


#多继承
class NoFootAnimal(object):
    def __init__(self):
        print "this is NoFootAnimal class"
    def show(self):
        print "show function"

class FootAnimal(object):
    def __init__(self):
        print "this is FoorAnimal class"
    def play(self):
        print "paly func"

class EyeAnimal(NoFootAnimal, FootAnimal):
    pass

eAnimal = EyeAnimal()
eAnimal.show()
eAnimal.play()


#简单的overload
class Fruit:
    def __init__(self, weight=0):
        self.weight = weight

    def __add__(self, other):
        return self.weight +  other.weight

    def __gt__(self, other):
        return self.weight > other.weight

class Apple(Fruit):
    pass

class Pear(Fruit):
    pass

app = Apple(23)
pear = Pear(45)
print "Apple's weight: ",app.weight
print "Pear's weight: ", pear.weight
print "Pear is weighter than apple?  : ",app>pear


#现在将以斜简单的工厂模式
class Factory:
    def createFruit(self, fruit):
        if fruit=="apple":
            return Apple()
        elif fruit == "pear":
            return Pear()

class Fruit:
    def __str__(self):
        return ""

class Apple(Fruit):
    def __str__(self):
        return "apple"

class Pear(Fruit):
    def __str__(self):
        return "pear"

fac = Factory()
print fac.createFruit("apple")

print fac.createFruit("pear")


QQ交流群: 204944806

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值