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

  >>> 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. [bzoj1910] [Ctsc2002] Award 颁奖典礼

    应该是第一次写这种图形类的DP.. 一个“I”可以分成三个矩形..令f[1..3][i][j][k]表示第几个矩形,下边界为第i行的j~k列,的最大面积. 然后就是各种优化啊什么的...时间复杂度O( ...

  2. BZOJ3930: [CQOI2015]选数

    题目:http://www.lydsy.com/JudgeOnline/problem.php?id=3930 容斥原理. 令l=(L-1)/k,r=R/k,这样找k的倍数就相当于找1的倍数. 设F[ ...

  3. 2017 ECJTU ACM 程序设计竞赛

    大厦 Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 65535/32768K (Java/Other) Total Submission ...

  4. <input type="text">和<textarea>的区别

    在我们开发时经常需要用到输入框,通常解决办法就是<input type="text">和<textarea>,那么这两个标签有什么区别呢?  一:<i ...

  5. Oracle:对表的CREATE、ALTER、INSERT、RENAME、DELETE操作练习以及主外键约束

    -创建一个student表,设定表的主键为学号CREATE TABLE student( sno VARCHAR2(10) PRIMARY KEY, --列级约束 sno VARCHAR2(20) C ...

  6. DEDECMS 留言薄模块的使用方法

    一.留言薄的安装 留言薄的安装过程和其他插件一样,首先我们进入后台模块管理列表,点击其对应的"安装": 以上步骤,我们完成了留言薄插件的安装. 二.留言薄的卸载 留言薄的卸载,同样 ...

  7. Uva10129 - Play on Words 欧拉通路 DFS

    题目链接: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=105& ...

  8. vue中引入jQuery和bootstrap

    一.引入jQuery: 首先在当前项目的根目录下(就是与package.json同目录),运行命令npm install jquery --save-dev   这样就将jquery安装到了这个项目中 ...

  9. struts异常:No result defined for action

    问题描述: No result defined for action com.freedom.funitureCityPSIMS.controller.login.CheckAction and re ...

  10. VC++ 6.0 中使用 MSComm.ocx

    很多人喜欢单独安装VC++6.0,而不是完整安装VS,这样占用空间比较少,启动也快.但是要使用某些ActiveX控件的时候却会出现许可证问题(requires a design-time licenc ...