【脚本语言系列】关于Python面向对象,你需要知道的事
来源:互联网 发布:计算机程序员考试 编辑:程序博客网 时间:2024/06/05 15:50
如何使用面向对象的方式进行设计
定义类/对象
# -*- coding:utf-8 -*-class Aeroplane(): passaeroplane = Aeroplane()
# -*- coding:utf-8 -*-class Aeroplane(): def __init__(self) passaeroplane = Aeroplane()
# -*- coding:utf-8 -*-class Aeroplane(): def __init__(self, name): self.name = nameaeroplane = Aeroplane("Allen Moore")print "Aeroplane's Name: ", aeroplane.name
Aeroplane's Name: Allen Moore
继承
# -*- coding:utf-8 -*-class Aeroplane(): passclass Boeing7x7(Aeroplane): passclass Airbus3x0(Aeroplane): passget_a_boeing = Boeing7x7()get_an_airbus = Airbus3x0()
# -*- coding:utf-8 -*-class Aeroplane(): def exclaim(self): print("I'm a Plane")class Boeing7x7(Aeroplane): passclass Airbus3x0(Aeroplane): passget_a_boeing = Boeing7x7()get_an_airbus = Airbus3x0()get_a_boeing.exclaim()get_an_airbus.exclaim()
I'm a PlaneI'm a Plane
重载
重载方法
# -*- coding:utf-8 -*-class Aeroplane(): def __init__(self, name): self.name = nameclass Boeing7x7(Aeroplane): def __init__(self, name): self.name = "Plane 7X7 "+nameclass Airbus3x0(Aeroplane): def __init__(self, name): self.name = "Plane 3X0 "+nameget_a_plane = Aeroplane("Normal") get_a_boeing = Boeing7x7("747")get_an_airbus = Airbus3x0("320")print "Plane Name: "+ get_a_plane.nameprint "Boeing Name: "+ get_a_boeing.nameprint "Airbus Name: "+ get_an_airbus.name
Plane Name: NormalBoeing Name: Plane 7X7 747Airbus Name: Plane 3X0 320
添加新成员
# -*- coding:utf-8 -*-# only for Python 3.xclass Aeroplane(): def __init__(self, name): self.name = nameclass Boeing7x7(Aeroplane): def __init__(self, name): self.name = "Plane 7X7 "+name def get_a_pulse(self): print "Get a Pulse"get_a_boeing = Boeing7x7("747")print get_a_boeing.get_a_pulse()
调用旧成员
# -*- coding:utf-8 -*-# only for Python 3.xclass Aeroplane(): def __init__(self, name): self.name = nameclass Boeing7x7(Aeroplane): def __init__(self, name, price): super(Boeing7x7,self).__init__() self.price = priceget_a_boeing = Boeing7x7("747",100)print get_a_boeing.nameprint get_a_boeing.price
---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-22-375953c61263> in <module>() 9 self.price = price 10 ---> 11 get_a_boeing = Boeing7x7("747",100) 12 print get_a_boeing.name 13 print get_a_boeing.price<ipython-input-22-375953c61263> in __init__(self, name, price) 6 class Boeing7x7(Aeroplane): 7 def __init__(self, name, price):----> 8 super(Boeing7x7,self).__init__() 9 self.price = price 10 TypeError: super() argument 1 must be type, not classobj
操作属性
设置属性
- property方法
# -*- coding:utf-8 -*-# only for Python 3.xclass Aeroplane(): def __init__(self, input_name): self.hidden_name =input_name def get_name(self): print "inside the getter, get the name" return self.hidden_name def set_name(self,input_name): print "inside the setter, set the name" self.hidden_name = input_name name = property(get_name, set_name)give_me_an_aeroplane = Aeroplane("Common Plane")print give_me_an_aeroplane.nameprint give_me_an_aeroplane.get_name()give_me_an_aeroplane.name='Uncle Allen'give_me_an_aeroplane.set_name("Uncle Allen")
inside the getter, get the nameCommon Planeinside the getter, get the nameCommon Planeinside the setter, set the name
- decorator修饰符
# -*- coding:utf-8 -*-# only for Python 3.xclass Aeroplane(): def __init__(self, input_name): self.hidden_name =input_name @property def name(self): print "inside the getter, get the name" return self.hidden_name @name.setter def name(self,input_name): print "inside the setter, set the name" self.hidden_name = input_namegive_me_an_aeroplane = Aeroplane("Common Plane")print give_me_an_aeroplane.namegive_me_an_aeroplane.name='Uncle Allen'print give_me_an_aeroplane.name
优点:
* 一处更改,处处更新
* 不设设置,不容设置
# -*- coding:utf-8 -*-# only for Python 3.xclass Aeroplane(): def __init__(self, name, size): self.name = name self.size = size @property def used_oils(self): return 100*self.sizegive_me_an_aeroplane = Aeroplane("Common Plane", 100)print give_me_an_aeroplane.used_oilsgive_me_an_aeroplane.size=10print give_me_an_aeroplane.used_oils
# -*- coding:utf-8 -*-# only for Python 3.xclass Aeroplane(): def __init__(self, name, size): self.name = name self.size = size @property def used_oils(self): return 100*self.sizegive_me_an_aeroplane = Aeroplane("Common Plane", 100)print give_me_an_aeroplane.used_oilsgive_me_an_aeroplane.size=10
10000
封装
保护私有特性
# -*- coding:utf-8 -*-# only for Python 3.xclass Aeroplane(): def __init__(self, input_name): self.__name =input_name @property def name(self): print "inside the getter, get the name" return self.__name @name.setter def name(self,input_name): print "inside the setter, set the name" self.__name = input_namegive_me_an_aeroplane = Aeroplane("Common Plane")print give_me_an_aeroplane.namegive_me_an_aeroplane.name="HQ Plane" print give_me_an_aeroplane.nameprint give_me_an_aeroplane._Aeroplane__name
inside the getter, get the nameCommon PlaneHQ PlaneCommon Plane
多态polymorphism
# -*- coding:utf-8 -*-# only for Python 3.xclass Aeroplane(): def __init__(self, name, size): self.name = name self.size = size def who(self): return self.name def which(self): return "xxx-"+self.sizeclass Airbus3x0(Aeroplane): def which(self): return "3x0-"+self.size class Boeing7x7(Aeroplane): def which(self): return "7x7-"+self.sizeplane = Aeroplane("Common Plane","0")print "Name: "+plane.who()print "Size: "+plane.which()planeA = Airbus3x0("Airbus","340")print "Name: "+planeA.who()print "Size: "+planeA.which()planeB = Boeing7x7("Boeing","747")print "Name: "+planeB.who()print "Size: "+planeB.which()def call_plane(obj): print "Name: "+obj.who()+"\n"+"Size: "+obj.which()call_plane(plane)call_plane(planeA)call_plane(planeB)
Name: Common PlaneSize: xxx-0Name: AirbusSize: 3x0-340Name: BoeingSize: 7x7-747Name: Common PlaneSize: xxx-0Name: AirbusSize: 3x0-340Name: BoeingSize: 7x7-747
对象之间的关系
组合 composition
聚合 aggregation
# -*- coding:utf-8 -*-class Color(): def __init__(self, color): self.color = colorclass Size(): def __init__(self, size): self.size = sizeclass Aeroplane(): def __init__(self, color, size): self.color = color self.size = size def about(self): print "The Fruit is ", color.color, "and ", size.sizecolor = Color("Yellow")size = Size("Big")aeroplane = Aeroplane(color, size)aeroplane.about()
The Fruit is Yellow and Big
其他
方法分类
实例方法(instance method)
类方法(class method)
# -*- coding:utf-8 -*-class Aeroplane(): count = 0 def __init__(self): Aeroplane.count += 1 def exclaim(self): print "This is an aeroplane." @classmethod def account(cls): print "They have ",cls.count," aeroplanes."aero_a = Aeroplane()aero_b = Aeroplane()aero_c = Aeroplane()print Aeroplane.account()
They have 3 aeroplanes.
- 静态方法(static method)
# -*- coding:utf-8 -*-class Aeroplane(): def __init__(self,name): self.name = name def exclaim(self): print "This is an aeroplane." @staticmethod def hello(): print "Welcome!"Aeroplane.hello()
Welcome!---------------------------------------------------------------------------NameError Traceback (most recent call last)<ipython-input-72-5eb75aa8c2ed> in <module>() 10 11 Aeroplane.hello()---> 12 hello()NameError: name 'hello' is not defined
特殊方法(special method)/魔术方法(magic method)
# -*- coding:utf-8 -*-class BarCodes(): def __init__(self, code): self.code = code def equals(self, code): return self.code.lower() == code.code.lower()first = BarCodes("ha")second = BarCodes("Ha")first.equals(second)
# -*- coding:utf-8 -*-class BarCodes(): def __init__(self, code): self.code = code def __eq__(self, code): return self.code.lower() == code.code.lower()first = BarCodes("ha")second = BarCodes("Ha")first == second
True
命名元祖
# -*- coding:utf-8 -*-from collections import namedtupleFruit = namedtuple("Fruit", "color size")fruit = Fruit('Yellow','Big')# fruit = Fruit(color="Yello",size="Big")print fruitprint fruit.colorprint fruit.sizeparts = {"color":"Yellow", "size":"Big"}fruit = Fruit(**parts)print fruitprint fruit.colorprint fruit.size# change key not allowed, change value allowedfruit1 = fruit._replace(color="Green", size="Big")print fruit1print fruit1.colorprint fruit1.size# add key-value partparts["status"]="Fresh"print partsfruit2 = Fruit(**parts)print fruit2print fruit2.colorprint fruit2.sizeprint fruit2.status
Fruit(color='Yellow', size='Big')YellowBigFruit(color='Yellow', size='Big')YellowBigFruit(color='Green', size='Big')GreenBig{'color': 'Yellow', 'status': 'Fresh', 'size': 'Big'}---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-31-5349e1cad48d> in <module>() 24 print parts 25 ---> 26 fruit2 = Fruit(**parts) 27 print fruit2 28 print fruit2.colorTypeError: __new__() got an unexpected keyword argument 'status'
阅读全文
0 0
- 【脚本语言系列】关于Python基础知识面向对象编程,你需要知道的事
- 【脚本语言系列】关于Python面向对象,你需要知道的事
- 【脚本语言系列】关于Python系统管理,你需要知道的事
- 【脚本语言系列】关于Python容器,你需要知道的事
- 【脚本语言系列】关于Python基础知识对象自省,你需要知道的事
- 【脚本语言系列】关于Python调试报错,你需要知道的事
- 【脚本语言系列】关于Python开发环境搭建,你需要知道的事
- 【脚本语言系列】关于Python数值计算NumPy, 你需要知道的事
- 【脚本语言系列】关于Python测试工具lettuce, 你需要知道的事
- 【脚本语言系列】关于Python测试工具mock, 你需要知道的事
- 【脚本语言系列】关于Python测试工具unittest, 你需要知道的事
- 【脚本语言系列】关于Python测试工具docstrings, 你需要知道的事
- 【脚本语言系列】关于Python测试工具Pyflakes, 你需要知道的事
- 【脚本语言系列】关于Python测试工具Pylint, 你需要知道的事
- 【脚本语言系列】关于Python性能分析工具timeit, 你需要知道的事
- 【脚本语言系列】关于Python代码分析工具line_profiler,你需要知道的事
- 【脚本语言系列】关于Python游戏工具Pygame,你需要知道的事
- 【脚本语言系列】关于Python机器学习scikits-learn,你需要知道的事
- CENTOS 6.5 配置YUM安装NGINX
- Spring-MVC入门-第一篇-DispatcherServlet浅谈
- 列表、元组、字典、引用的一些操作(数据结构)--python学习(3)
- python3之正则表达式
- NAS实现类型对比
- 【脚本语言系列】关于Python面向对象,你需要知道的事
- 和为S的连续正数序列
- django-ckeditor表情包修改
- js获取当前时间并转变格式
- 阿里GTS原理分析
- python学习8------高阶函数
- 从零开始学习音视频编程技术(32) Linux篇之编译和链接
- 【个人笔记重点,不作为参考】主题:angular2有关对象的注意事项
- LeetCode 152. Maximum Product Subarray(最大连续乘积)