zoukankan      html  css  js  c++  java
  • Python基础篇(七)

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

      >>> 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]

  • 相关阅读:
    LeetCode#237 Delete Node in a Linked List
    数据库概念
    请基于 TCP/IP 五层网络模型描述下当我们在浏览器请求 https ://pp.io 站点时,发生了哪些事情
    高并发大流量
    mysql关于索引
    php基础——会话控制
    php基础——运算符知识
    php基础——常量及数据类型考察
    引用变量和cow机制
    关系基本特性的运算封闭性
  • 原文地址:https://www.cnblogs.com/lnlvinso/p/3903025.html
Copyright © 2011-2022 走看看