標籤:java 使用 os io for ar div line
加上兩個底線變數或者方法變為私人。
>>> 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]