【脚本语言系列】关于Python基础知识面向对象编程,你需要知道的事
2017-06-09 22:32
1161 查看
如何进行面向对象编程
类和对象
# -*- coding:utf-8 -*- # create the class class Animal: def grow(self): print "Animal grow..." if __name__ == "__main__": animal = Animal() animal.grow()
Animal grow...
# -*- coding:utf-8 -*- # display the class attribute&the instance attribute class Animal: price = 0 def __init__(self): self.color = "black" zone = "China" if __name__ == "__main__": print Animal.price duck = Animal() print duck.color Animal.price = Animal.price + 10 print "duck's price:"+str(duck.price) chick = Animal() print "chick's price:" + str(chick.price)
0 black duck's price:10 chick's price:10
属性和方法
# -*- coding:utf-8 -*- # display the class attribute&the instance attribute class Animal: price = 0 def __init__(self): self.__color = "black" zone = "China" if __name__ == "__main__": duck = Animal() print duck._Animal__color
# -*- coding:utf-8 -*- # display the class attribute&the instance attribute class Animal: def __init__(self): self.__color = "black" class Duck(Animal): pass if __name__ == "__main__": animal = Animal() duck = Duck() print Duck.__bases__ print duck.__dict__ print duck.__module__ print duck.__doc__
# -*- coding:utf-8 -*- # display the class attribute&the instance attribute class Animal: def __init__(self): self.__color = "black" class Duck(Animal): pass if __name__ == "__main__": animal = Animal() duck = Duck() print Duck.__bases__ print duck.__dict__ print duck.__module__ print duck.__doc__
# -*- coding:utf-8 -*- # display the static mathod class Animal: price = 0 def __init__(self): self.__color = "red" def getColor(self): print self.__color @ staticmethod def getPrice(): print Animal.price def __getPrice(): Animal.price = Animal.price + 10 print Animal.price count = staticmethod(__getPrice) if __name__ == "__main__": duck = Animal() duck.getColor() Animal.count() chick = Animal() chick.count() chick.getPrice()
red 10 20 20
# -*- coding:utf-8 -*- # display the class mathod class Animal: price = 0 def __init__(self): self.__color = "red" def getColor(self): print self.__color @ classmethod def getPrice(self): print Animal.price def __getPrice(self): Animal.price = self.price + 10 print self.price count = classmethod(__getPrice) if __name__ == "__main__": duck = Animal() duck.getColor() Animal.count() chick = Animal() chick.count() chick.getPrice()
# -*- coding:utf-8 -*- # display the inside class class Bus: class Door: def open(self): print "open door" class Wheel: def run(self): print "Bus run" if __name__ == "__main__": bus = Bus() backDoor = Bus.Door() frontDoor = Bus.Door() backDoor.open() frontDoor.open() wheel = Bus.Wheel() wheel.run()
# -*- coding:utf-8 -*- # display the __init__ method class Bus: def __init__(self, color): self.__color = color print self.__color def getColor(self): print self.__color def setColor(self, color): self.__color = color print self.__color if __name__ == "__main__": color = "red" bus = Bus(color) bus.getColor() bus.setColor("blue")
red red blue
# -*- coding:utf-8 -*- # display the __del__ method class Bus: def __init__(self, color): self.__color = color print self.__color def __del__(self): self.__color = "" print "free..." def grow(self): print "grow..." if __name__ == "__main__": color = "red" bus = Bus(color) bus.grow()
red free... grow...
# -*- coding:utf-8 -*- import gc # display the garbage collection class Bus: def __init__(self, name, color): self.__name = name self.__color = color def getColor(self): return self.__color def setColor(self, color): self.__color = color def getName(self): return self.__name def setColor(self, name): self.__name = name class BusShop: def __init__(self): self.buses = [] def addBus(self, bus): bus.parent = self self.buses.append(bus) if __name__ == "__main__": shop = BusShop() shop.addBus(Bus("small", "red")) shop.addBus(Bus("big", "yellow")) print gc.get_referrers(shop) del shop print gc.collect()
[{'_Bus__color': 'red', 'parent': <__main__.BusShop instance at 0x000000000347C288>, '_Bus__name': 'small'}, {'_Bus__color': 'yellow', 'parent': <__main__.BusShop instance at 0x000000000347C288>, '_Bus__name': 'big'}, ... ... ... print gc.get_referrers(shop)\n del shop\n print gc.collect()'], '_oh': {}, 'Out': {}}] 41
# -*- coding:utf-8 -*- # display the __new__ method class Singleton(object): __instance = None def __init__(self): pass def __new__(cls, *args, **kwd): if Singleton.__instance is None: Singleton.__inistance = object.__new__(cls, *args, **kwd) return Singleton.__instance
# -*- coding:utf-8 -*- # display the __getattr__and__setattr__ method class Bus(object): def __init__(self, color = "red", price = 0): self.__color = color self.__price = price def __getattribute__(self, name): return object.__getattribute__(self, name) def __setattr__(self, name, value): self.__dict__[name] = value if __name__ == "__main__": bus = Bus("blue", 10) print bus.__dict__.get("_Bus__color") bus.__dict__["_Bus__price"] = 5 print bus.__dict__.get("_Bus__price")
blue 5
# -*- coding:utf-8 -*- # display the __getitem__ method class BusShop: def __getitem__(self, i): return self.buses[i] if __name__ == "__main__": shop = BusShop() shop.buses = ["small", "big"] print shop[1] for item in shop: print item,
big small big
# -*- coding:utf-8 -*- # display the __str__ method class Bus: "Bus class" def __str__(self): return self.__doc__ if __name__ == "__main__": bus = Bus() print str(bus)
Bus class
# -*- coding:utf-8 -*- # display the __call__ method class Bus: class Aging: def __call__(self): print "aging..." aging = Aging() if __name__ == "__main__": bus = Bus() bus.aging() Bus.aging()
aging... aging...
# -*- coding:utf-8 -*- # display the __call__ method class Bus: pass def add(self): print "aging..." if __name__ == "__main__": Bus.age = add bus = Bus() bus.age()
# -*- coding:utf-8 -*- # display the __call__ method class Bus: def aging(self): print "aging..." def update(): print "aging......" if __name__ == "__main__": bus = Bus() bus.aging() bus.aging = update bus.aging()
aging... aging......
继承
# -*- coding:utf-8 -*- # display the inherit class Car: def __init__(self, color): self.color = color print "Car's color: %s" %self.color def aging(self): print "aging ..." class Bus(Car): def __init__(self, color): Car.__init__(self, color) print "Bus's color: %s" %self.color class Jeep(Car): def __init__(self, color): Car.__init__(self, color) print "Jeep's color: %s" %self.color def aging(self): print "Jeep aging..." if __name__ == "__main__": bus = Bus("red") bus.aging() jeep = Jeep("yellow") jeep.aging()
fruit's color: red Bus's color: red aging ... fruit's color: yellow Jeep's color: yellow Jeep aging...
# -*- coding:utf-8 -*- # display the inherit class Car(object): def __init__(self): print "parent" class Bus(Car): def __init__(self): super(Car, self).__init__() print "child" if __name__ == "__main__": Bus()
child
# -*- coding:utf-8 -*- # display the abstract class def abstract(): raise NotImplementedError("abstract") class Car(object): def __init__(self): if self.__class__ is Car: abstract() print "Car" class Bus(Car): def __init__(self): Car.__init__(self) print "Bus" if __name__ == "__main__": bus = Bus() car = Car()
Car Bus ---------------------------------------------------------------------- NotImplementedError Traceback (most recent call last) <ipython-input-34-e90b06815f95> in <module>() 17 if __name__ == "__main__": 18 bus = Bus() ---> 19 car = Car() <ipython-input-34-e90b06815f95> in __init__(self) 7 def __init__(self): 8 if self.__class__ is Car: ----> 9 abstract() 10 print "Car" 11 <ipython-input-34-e90b06815f95> in abstract() 2 # display the inherit 3 def abstract(): ----> 4 raise NotImplementedError("abstract") 5 6 class Car(object): NotImplementedError: abstract
# -*- coding:utf-8 -*- # display the morphology class Car: def __init__(self, color=None): self.color = color class Bus(Car): def __init__(self, color="red"): Car.__init__(self, color) class Jeep(Car): def __init__(self, color = "yellow"): Car.__init__(self, color) class CarShop: def sellCar(self, car): if isinstance(car, Bus): print "sell bus" if isinstance(car, Jeep): print "sell jeep" if isinstance(car, Car): print "sell car" if __name__ == "__main__": shop = CarShop() bus = Bus("red") jeep = Jeep("yellow") shop.sellCar(bus) shop.sellCar(jeep)
sell bus sell car sell jeep sell car
# -*- coding:utf-8 -*- # display the multi-inherit class Car(object): def __init__(self): print "initialize Car" def aging(self): print "aging..." class Suv(object): def __init__(self, color="red"): Car.__init__(self, color) def jumping(self): print "jumping..." class Jeep(Car, Suv): pass if __name__ == "__main__": jeep = Jeep() jeep.aging() jeep.jumping()
initialize Car aging... jumping...
# -*- coding:utf-8 -*- # display the multi-inherit class Car(object): def __init__(self): pass class SpeedCar(Car): def __init__(self): print "initialize SpeedCar" def speed(self): print "speed..." class JumpCar(Car): def __init__(self): print "initialize JumpCar" def jump(self): print "jump..." class Bus(SpeedCar): pass class Jeep(JumpCar): pass
# -*- coding:utf-8 -*- # display the multi-inherit class Car(object): def __init__(self): pass class SpeedCar(object): def __init__(self): print "initialize SpeedCar" def speed(self): print "speed..." class JumpCar(object): def __init__(self): print "initialize JumpCar" def jump(self): print "jump..." class Bus(SpeedCar,Car): pass class Jeep(JumpCar,Car): pass
# -*- coding:utf-8 -*- # reload the operator class Car(object): def __init__(self,price=0): self.price = price def __add__(self, other): return self.price + other.price def __gt__(self, other): if self.price > other.price: flag = True else: flag = False return flag class Bus(Car): pass class Jeep(Car): pass if __name__== "__main__": bus = Bus(3) print "bus's price:", bus.price jeep = Jeep(3) print "jeep's price:", jeep.price print jeep > bus total = bus + jeep print "total: ", total
bus's price: 3 jeep's price: 3 False total: 6
# -*- coding:utf-8 -*- import sys # reload the operator class Stream: def __init__(self, file): self.file = file def __lshift__(self, obj): self.file.write(str(obj)) return self class Car(Stream): def __init__(self, price = 0, file = None): Stream.__init__(self, file) self.price = price class Bus(Car): pass class Jeep(Car): pass if __name__== "__main__": bus = Bus(2, sys.stdout) jeep = Jeep(3, sys.stdout) endl = "\n" bus << bus.price << endl jeep << jeep.price << endl
2 3
什么是面向对象
面向对象是一种方法学。面向对象是一种描述业务问题的方法。面向对象技术已经成为当今软件设计和开发领域的主流技术。
相关文章推荐
- 【脚本语言系列】关于Python基础知识对象自省,你需要知道的事
- 【脚本语言系列】关于Python基础知识兼容Python 2.x+Python 3.x,你需要知道的事
- 【脚本语言系列】关于Python基础知识装饰器,你需要知道的事
- 【脚本语言系列】关于Python基础知识迭代器,你需要知道的事
- 【脚本语言系列】关于Python基础知识异常处理,你需要知道的事
- 【脚本语言系列】关于Python基础知识多返回值,你需要知道的事
- 【脚本语言系列】关于Python基础知识调试,你需要知道的事
- 【脚本语言系列】关于Python基础知识魔法变量,你需要知道的事
- 【脚本语言系列】关于Python基础知识协程,你需要知道的事
- 【脚本语言系列】关于Python基础知识文件操作,你需要知道的事
- 【脚本语言系列】关于Python基础知识函数缓存,你需要知道的事
- 【脚本语言系列】关于Python基础知识容器,你需要知道的事
- 【脚本语言系列】关于Python基础知识Lambda表达式,你需要知道的事
- 【脚本语言系列】关于Python基础知识枚举,你需要知道的事
- 【脚本语言系列】关于Python基础知识处理字符串,你需要知道的事
- 【脚本语言系列】关于Python基础知识__slots__,你需要知道的事
- 【脚本语言系列】关于Python基础知识推导式,你需要知道的事
- 【脚本语言系列】关于Python基础知识设计模式,你需要知道的事
- 【脚本语言系列】关于Python基础知识映射器和过滤器,你需要知道的事
- 【脚本语言系列】关于Python基础知识对象变动,你知道的事