python类的使用3

来源:互联网 发布:python os.execv 编辑:程序博客网 时间:2024/06/03 20:32
#!/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 0
原创粉丝点击