加上两个下划线变量或者方法变为私有。

  >>> class Bird:

  ...    __song = "spark"

  ...    def sing(self):

  ...       return self.__song

  ...

  >>> b = Bird()

  >>> b.sing()

  'spark'

  >>> b.__sing()

  Traceback (most recent call last):

   File "<stdin>", line 1, in <module>

  AttributeError: 'Bird' object has no attribute '__sing'

  实际上,上面的__song定义为私有的,无法直接访问,但是通过下面的方式还是可以得到的:

  >>> b._Bird__song

  'spark'

  成员变量与类变量的区别

  >>> class NumberCount:

  ...    number = 0

  ...    def count(self):

  ...        self.number = self.number + 1

  ...

  >>> n = NumberCount()

  >>> n.count()

  >>> n.number

  1

  >>> num = NumberCount()

  >>> num.count()

  >>> num.number

  1

  >>> class NumberCount:

  ...    number = 0

  ...    def count(self):

  ...        NumberCount.number = NumberCount.number + 1

  ...

  >>> n = NumberCount()

  >>> n.count()

  >>> n.number

  1

  >>> num = NumberCount()

  >>> num.count()

  >>> num.number

  2

  类之间的继承关系

  >>> class Filter:

  ...    def init(self):

  ...        self.block = []

  ...    def filter(self,sequence):

  ...        return [x for x in sequence if x not in self.block]

  ...

  >>> f = Filter()

  >>> f.init()

  >>> f.filter(["1","2","3"])

  ['1', '2', '3']

  >>> class SubFilter(Filter):

  ...    def init(self):

  ...        self.block = ["FDD"]

  ...

  >>> s = SubFilter()

  >>> s.init()

  >>> s.filter(["FDD","1","2"])

  ['1', '2']

  判断一个类是否是另一个类的子类

  >>> issubclass(SubFilter,Filter)

  True

  用__class__或者type函数来判断一个实例属于哪个类:

  >>> s.__class__

  <class '__main__.SubFilter'>

  >>> type(s)

  <class '__main__.SubFilter'

  多继承

  >>> class Calculator:

  ...    def cal(self,expression):

  ...        self.value = eval(expression)

  ...

  >>> class Talker:

  ...     def talk(self):

  ...        print("the result of what you input is ",self.value)

  ...

  >>> class Test(Calculator,Talker):

  ...   pass

  ...

  >>> t = Test()

  >>> t.cal("3*788 + 999")

  >>> t.talk()

  the result of what you input is  3363

  通过实例来判断类是否有某个方法:

  >>> hasattr(t,"talk")

  True

  Python中异常的处理:

  >>> try:

  ...     x = input("enter the first number: ")

  ...     y = input("enter the second number: ")

  ...     print((int)(x)/(int)(y))

  ... except ZeroDivisionError:

  ...     print("the second number can not be zero")

  ...

  enter the first number: 10

  enter the second number: 0

  the second number can not be zero

  使用raise继续抛出异常

  >>> class HideException:

  ...   isHide = False

  ...   def cal(self,expression):

  ...       try:

  ...           return eval(expression)

  ...       except ZeroDivisionError:

  ...           if self.isHide:

  ...              print("the second number can not be zero")

  ...           else:

  ...              raise

  ...

  >>> r = HideException()

  >>> r.cal("3/0")

  Traceback (most recent call last):

   File "<stdin>", line 1, in <module>

    File "<stdin>", line 5, in cal

    File "<string>", line 1, in <module>

  ZeroDivisionError: division by zero

  >>> r.isHide = true

  Traceback (most recent call last):

   File "<stdin>", line 1, in <module>

  NameError: name 'true' is not defined

  >>> r.isHide = True

  >>> r.cal("3/0")

  the second number can not be zero

  打开屏蔽,则按自己的定义输出。关闭屏蔽,抛出异常。

  定义自己的异常:

  >>> class MyException(Exception):pass

  ...

  同时捕获多个异常

  >>> class DivideTest:

  ...    try:

  ...        x = input("enter the first member: ")

  ...        y = input("enter the second member: ")

  ...        print(int(x)/int(y))

  ...    except (ZeroDivisionError,TypeError,NameError):

  ...        print("input was wrong")

  ...

  enter the first member: 10

  enter the second member: 0

  input was wrong

  捕获错误信息e

  >>> class DivideTest:

  ...    try:

  ...        x = input("enter the first member: ")

  ...        y = input("enter the second member: ")

  ...        print(int(x)/int(y))

  ...    except (ZeroDivisionError,TypeError,NameError) as e:

  ...        print(e)

  ...

  enter the first member: 10

  enter the second member: 0

  division by zero

  捕获全部的异常

  >>> class DivideTest:

  ...    try:

  ...        x = input("enter the first member: ")

  ...        y = input("enter the second member: ")

  ...        print(int(x)/int(y))

  ...    except Exception as e:

  ...        print(e)

  ...

  enter the first member: 10

  enter the second member: 0

  division by zero

  finally语句,始终会被执行

  >>> x= None

  >>> try:

  ...    x = 1/0

  ... finally:

  ...    print("whatever will be excuted!")

  ...

  whatever will be excuted!

  Traceback (most recent call last):

   File "<stdin>", line 2, in <module>

  ZeroDivisionError: division by zero

  和Java不同的是,Python子类不会默认调用父类的构造函数,需要显示的使用super函数取调用父类的构造函数。

  >>> class Bird:

  ...    def __init__(self):

  ...        self.hungry = True

  ...    def eat(self):

  ...        if self.hungry:

  ...           print("eating")

  ...           self.hungry = False

  ...        else:

  ...           print("Full")

  ...

  >>> b = Bird()

  >>> b.eat()

  eating

  >>> b.eat()

  Full

  >>> class SingBird(Bird):

  ...     def __init__(self):

  ...         self.song = "sqawk"

  ...     def sing(self):

  ...         print(self.song)

  ...

  >>> s = SingBird()

  >>> s.sing()

  sqawk

  >>> s.eat()

  Traceback (most recent call last):

   File "<stdin>", line 1, in <module>

  File "<stdin>", line 5, in eat

  AttributeError: 'SingBird' object has no attribute 'hungry'

  >>> class SingBird(Bird):

  ...     def __init__(self):

  ...         super(SingBird,self).__init__()

  ...         self.song = "sqawk"

  ...     def sing(self):

  ...         print(self.song)

  ...

  >>> s = SingBird()

  >>> s.sing()

  sqawk

  >>> s.eat()

  eating

  >>> class SingBird(Bird):

  不使用super函数而直接调用父类的构造方法也是可以的

  >>> class sBird(Bird):

  ...    def __init__(self):

  ...        Bird.__init__(self)

  ...        self.song = "sqwak"

  ...    def sing(self):

  ...        print(self.song)

  ...

  >>> ss = sBird()

  >>> ss.eat()

  eating

  >>> ss.eat()

  Full

  Python的语句相对Java是比较灵活的

  >>> for key,value in dire.items():

  ...     print(key,value)

  可以直接写语句,写方法,写类。不像Java,语句肯定是位于类的方法中的。

  使用Python的内建类型list:

  >>> class CounterList(list):

  ...     def __init__(self,*args):

  ...         super(CounterList,self).__init__(*args)

  ...

  >>> cl = CounterList(range(10))

  >>> cl

  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Python基础篇(七)的更多相关文章

  1. python基础篇(六)

    PYTHON基础篇(六) 正则模块re A:正则表达式和re模块案例 B:re模块的内置方法 时间模块time A:时间模块的三种表示方式 B:时间模块的相互转换 随机数模块random A:随机数模 ...

  2. python基础篇(文件操作)

    Python基础篇(文件操作) 一.初始文件操作 使用python来读写文件是非常简单的操作. 我们使用open()函数来打开一个文件, 获取到文件句柄. 然后通过文件句柄就可以进行各种各样的操作了. ...

  3. Python基础篇(五)_文件和数据格式化

    Python基础篇_文件和数据格式化 文件的使用:文件打开.关闭.读写 文件打开:通过open()函数打开文件,并返回一个操作文件的变量. 使用语法:<变量名> = (<文件路径以及 ...

  4. python基础篇-day1

    python基础篇 python是由C语言写的: pass 占位符: del,python中全局的功能,删除内存中的数据: 变量赋值的方法: user,pass = 'freddy','freddy1 ...

  5. python基础篇之进阶

    python基础篇之进阶 参考博客:http://www.cnblogs.com/wupeiqi/articles/5115190.html python种类 1. cpython  使用c解释器生产 ...

  6. python基础篇(五)

    PYTHON基础篇(五) 算法初识 什么是算法 二分查找算法 ♣一:算法初识 A:什么是算法 根据人们长时间接触以来,发现计算机在计算某些一些简单的数据的时候会表现的比较笨拙,而这些数据的计算会消耗大 ...

  7. python基础篇(一)

    PYTHON基础篇(一) 变量 赋值 输入,输出和导入 A:输入 B:输出 C:导入 运算符 A:算数运算符 B:比较运算符 C:赋值运算符 D:位运算符 E:逻辑运算符 F:成员运算符 G:身份运算 ...

  8. python基础篇(二)

    PYTHON基础篇(二) if:else,缩进 A:if的基础格式和缩进 B:循环判断 C:range()函数和len()函数 D:break,contiue和pass语句 for,while循环 函 ...

  9. python基础篇(三)

    PYTHON基础篇(三) 装饰器 A:初识装饰器 B:装饰器的原则 C:装饰器语法糖 D:装饰带参数函数的装饰器 E:装饰器的固定模式 装饰器的进阶 A:装饰器的wraps方法 B:带参数的装饰器 C ...

  10. python基础篇(四)

    PYTHON基础篇(四) 内置函数 A:基础数据相关(38) B:作用域相关(2) C:迭代器,生成器相关(3) D:反射相关(4) E:面向对象相关(9) F:其他(12) 匿名函数 A:匿名函数基 ...

随机推荐

  1. Vijos P1131 最小公倍数和最大公约数问题【暴力】

    最小公倍数和最大公约数问题 描述 输入二个正整数x0,y0(2≤x0≤100000,2≤y0≤1000000),求出满足下列条件的P.Q的个数. 条件:1.P.Q是正整数 2.要求P.Q以xO为最大公 ...

  2. Bellman-Ford 求含负权最短路

    该算法详解请看   https://www.cnblogs.com/tanky_woo/archive/2011/01/17/1937728.html 单源最短路   当图中存在负权边时 迪杰斯特拉就 ...

  3. Kafka监控安装

    p.MsoNormal { margin: 0pt; margin-bottom: .0001pt; text-align: justify; font-family: Calibri; font-s ...

  4. post请求测试

    也可以用下图来指定测试参数

  5. javascript如何处理多级的实时监听

    今日工作中遇到需求,要求js代码对表单中的input内容进行实时监听,当input中的值改变时触发一些事件. 按照常规思维,代码很快写完了. $(function () { $("#inpu ...

  6. 好的Qt学习资料

    1.青春不老,奋斗不止!---CSDN博客地址http://blog.csdn.net/liang19890820:

  7. xshell连接虚拟机Ubuntu问题

    近期为了学习数据库的操作,准备在虚拟机中搭建环境以便操作(为什么在虚拟机搭建学习环境?),系统刚装好第一步就被阻止了. 总是会提示Could not connect to.原因是虚拟机没有安装ssh服 ...

  8. 初识RabbitMQ,附RabbitMQ+PHP演示实例

    RabbitMQ是一个在AMQP基础上实现的企业级消息系统.何谓消息系统,就是消息队列系统,消息队列是""消费-生产者模型""的一个典型的代表,一端往消息队列中 ...

  9. vue-cli脚手架的.babelrc文件 详解

    { // 此项指明,转码的规则 "presets": [ // env项是借助插件babel-preset-env,下面这个配置说的是babel对es6,es7,es8进行转码,并 ...

  10. Python 3 利用 Dlib 19.7 和 sklearn机器学习模型 实现人脸微笑检测

    0.引言  利用机器学习的方法训练微笑检测模型,给一张人脸照片,判断是否微笑:   使用的数据集中69张没笑脸,65张有笑脸,训练结果识别精度在95%附近: 效果: 图1 示例效果 工程利用pytho ...