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

  >>> 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. [hdu5225][BC#40]Tom and permutation

    好久没写题解了..GDKOI被数位DP教做人了一发,现在终于来填数位DP的大坑了>_<. 发现自己以前写的关于数位DP的东西...因为没结合图形+语文水平拙计现在已经完全看不懂了嗯. 看来 ...

  2. win10清除桌面快捷方式小箭头

    reg add /d "%systemroot%\system32\imageres.dll,197" /t reg_sz /f taskkill /f /im explorer. ...

  3. C++ 不定参数(转)

    转自:http://www.cnblogs.com/jerrychenfly/archive/2010/10/22/1858232.html 下面,我们来看一下,如果在c++的函数中接收数量不定的函数 ...

  4. dedecms下的tplcache模板缓存文件过多怎么清理?

    时间:2016-04-18 09:32来源:www.ucbug.cc作者:网络 相信很多站长,或者seoer人员在备份用dedecms程序开发的网站时,发现下载到tplcache这个文件夹内容时候花了 ...

  5. move_uploaded_file

    move_uploaded_file() 函数将上传的文件移动到新位置. 若成功,则返回 true,否则返回 false. 语法 move_uploaded_file(file,newloc) 参数 ...

  6. 2.移植3.4内核-使内核支持烧写yaffs2

    在上章-制作文件系统,并使内核成功启动jffs2文件系统了 本章便开始使内核支持烧写yaffs2文件系统 1.首先获取yaffs2源码(参考git命令使用详解) cd /work/nfs_root g ...

  7. 邓_PHP面试【001】

    1.双引号和单引号的区别 双引号解释变量,单引号不解释变量 双引号里插入单引号,其中单引号里如果有变量的话,变量解释 双引号的变量名后面必须要有一个非数字.字母.下划线的特殊字符,或者用{}讲变量括起 ...

  8. Block 的使用时机

    Block 一般是用来表示.简化一小段的程式码,它特别适合用来建立一些同步执行的程式片段.封装一些小型的工作或是用来做为某一个工作完成时的回传呼叫(callback) . 在新的iOS API中blo ...

  9. Android-第一天

    1.google 2.application->application framework->libraries(调用关系) 3.strings.xml 是全局字符串的配置文件 4.ADT ...

  10. python_如何对字典进行排序?

    案例: 某班英语成绩以字典的形式存储为: {'lili':78, 'jin':50, 'liming': 30, ......} 依据成绩高低,进行学生成绩排名 如何对字典排序? 方法1: #!/us ...