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

  >>> 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. Codeforces Round #336 (Div. 2)【A.思维,暴力,B.字符串,暴搜,前缀和,C.暴力,D,区间dp,E,字符串,数学】

    A. Saitama Destroys Hotel time limit per test:1 second memory limit per test:256 megabytes input:sta ...

  2. Spring框架学习笔记(10)——Spring中的事务管理

    什么是事务 举例:A给B转500,两个动作,A的账户少500,B的账户多500 事务就是一系列的动作, 它们被当做一个单独的工作单元. 这些动作要么全部完成, 要么全部不起作用 一.注解添加事务管理方 ...

  3. 前端自动化-----gulp详细入门(转)

    简介: gulp是前端开发过程中对代码进行构建的工具,是自动化项目的构建利器:她不仅能对网站资源进行优化,而且在开发过程中很多重复的任务能够使用正确的工具自动完成:使用她,我们不仅可以很愉快的编写代码 ...

  4. VMware workstation 虚拟机中安装乌班图及其兼容性问题

    之前我在虚拟机中安装乌班图,是先安装好虚拟机,然后将预先下载好的乌班图镜像文件导入安装,这样安装起来还是有些繁琐的,中间要设置好多东西.今天领导给我拷了个虚拟机,还有乌班图的安装文件,是这样的. 对于 ...

  5. O2O网站

    编辑 020是新型的网络营销模式,O2O即Online To Offline,线下销售与服务通过线上推广来揽客,消费者可以通过线上来筛选需求,在线预订.结算,甚至可以灵活地进行线上预订,线下交易.消费 ...

  6. 【编程技巧】ExtJs 设置GridPanel表格文本垂直居中

    详细讲解见 http://blog.csdn.net/li396864285/article/details/9310983 以下是我改修的代码: {         width:90,        ...

  7. Java Draw

    简单绘画 直线 矩形 圆 根据矩阵画图 package com.zhoudm; import java.awt.*; import javax.swing.*; public class Draw e ...

  8. java.lang.reflect.InvocationTargetException

    java.lang.reflect.InvocationTargetException是什么情况?java.lang.reflect.InvocationTargetExceptionat sun.r ...

  9. 一分钟搭建Vue2.0+Webpack2.0多页面项目

    想要自己一步步搭建的比较麻烦,不是很推荐,最少也要使用vue-cli,在其基础上开始搭建,今天我的主题是一分钟搭建,那么常规方法肯定不能满足的, 而我用的方法也很简单,就是使用已经配置完成的demo模 ...

  10. 一次线上tomcat应用请求阻塞的排查经过

    今天早上,收到一个报警,有个服务器的http往返时延飙升,同时曝出大量404,很是折腾了一番,特记录下思考和排查经过. 1.这是单纯的时延增大,还是有什么其他情况还未掌握? 因为不知道是只有时延变大而 ...