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]

原文地址:https://www.cnblogs.com/lnlvinso/p/3903025.html