物聯網平台開發人才平日班

物聯網平台開發人才平日班
物聯網平台開發人才 平日密集訓練班 - 106年招生簡章下載(待業限定)

2017年3月9日 星期四

Python 入門學習快速筆記 (五)

類別

class Demo:
   
        i=0   # 類別變數
        def __init__(self, name):
                self.name=name    # self.name 實體變數
        def showvalue(self):
                print("hello",self.i)

        def showname(self):
                print("hello",self.name)


private variable 或 private_method 在名稱前面加上 __
__variable
__function

Private value

Traceback (most recent call last): File "C:/Python34/aaa.py", line 33, in <module> print(a.__y) # private attribute AttributeError: 'Demo' object has no attribute '__y'



200 Traceback (most recent call last): File "C:/Python34/aaa.py", line 25, in <module> print(a.i) AttributeError: 'Demo' object has no attribute 'i'


Traceback (most recent call last): File "C:/Python34/aaa.py", line 25, in <module> print(a.__i) AttributeError: 'Demo' object has no attribute '__i'

==========================================


封裝 


public data, private datapublic function, private function


==========================================


類別多重繼承

子類別(subclass)能夠繼承(inherit) 多個父類別,使子類別可以有多種特性。
  • 當子類別繼承(inheritance)超過一個來源的時候,會以寫在最左邊的父類別優先繼承,這是說,多個父類別如果有相同名稱的屬性(attribute)與方法(method),例如init()、str__()等,就會以最左邊的父類別優先。


==========================================

多型(polymorphism) 與抽象方法( Abstract method)


class Animal: def __init__(self, name): # Constructor of the class self.name = name def talk(self): # Abstract method, defined by convention only raise NotImplementedError("Subclass must implement abstract method") class Cat(Animal): def talk(self): return 'Meow!' class Dog(Animal): def talk(self): return 'Woof! Woof!' class Fish(Animal): pass animals = [Cat('Missy'), Cat('Garfield'), Dog('Lassie'),Fish('Gold')] for animal in animals: print(animal.name + ': ' + animal.talk())


Traceback (most recent call last): File "D:\Python_lecturer_NTU\python code\python code\EX05_08.py", line 20, in <module> print(animal.name + ': ' + animal.talk()) File "D:\Python_lecturer_NTU\python code\python code\EX05_08.py", line 5, in talk raise NotImplementedError("Subclass must implement abstract method") NotImplementedError: Subclass must implement abstract method

沒有留言 :

張貼留言