Thursday, October 6, 2016

[ Objected-Oriented Programming ]Properties

Properties

  • provide a way to customizing access to instance attributes.
  • defining setter / getter functions
    • @egg.setter
read only ??

>>>
class Pizza:
  def__init__(self, toppings):
    self.toppings = toppings

  @property 
  def pinapple_allowed(self):
    return False


pizza = Pizza(["cheese","tomato"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed = True

[ Objected-Oriented Programming ] Class & Static Methods

Instance of a class 

  • passed to the self parameter of the method

Class methods

  • called by a class, which is passed to the cls parameter of the method
>>>
class Rectangle:
  def__init__(self,width,height):
    self.width = width
    self.height = height

  def calculate_area(self)
    return self.width*self.height


  @classmethod
  def new_square(cls, side_length):
    return cls(side_length , side_length)


square = Recangle.new_square(5)
print(square.calculate_area())


>>>
25

new_square is a class method and is called on the class , rather than on an instance of the class.It returns a new object of the class cls.


Static methods
  • similar to class method ,except they don;t receive any additional arguments
  • behave like plain fuction
  • @staticmethod

[ Objected-Oriented Programming ] Data Hiding*

Encapsulation


  • private method in Python => A method external code is discouraged from using.
  • the purpose of prefacing a method name with a single underscore => To mark it as private , but not prevent it being called by external code
  • double underscore => strongly private methods  , that they can't be access from outside the class, the purpose of this isn't to ensure that they are kept private , but to avoid bugs if there are subcalss that have methods pr attribute with the same names

>>>
class Spam:
  __egg =7
  def print_egg(self):
    print(self._egg)

s = Spam()
s.print_egg()
print(s.Spam_egg)
print(s._egg)

>>>
7
7
AttibuteError


[ Objected-Oriented Programming ] Object Lifecycle

The lifecycle of  an object is made up of its
Creation , Manipulation, Destruction

 life-cycle

  1. definition
  2. instantiation => __init__
  3. __new__
  4. object s ready to use
  5. destroyed =>reference count , del  -> delete instance, garbage collection

Lower level languages like C don't have this kind of automatic memory management

[ Objected-Oriented Programming ] Magic Methods & Operator Overloading*

Magic Method

  • special method which have double underscores at the beginning and the end of their names.
  • They also known as dunders.
  • ~ __init__
  • they are used to create functionality that can't be represented as a normal method
  • One common use of the m is operator overloading

>>>
class Vector2D:
  def__init__(self,x,y):
    self.x = x
    self.y = y

  def__add__(self,other):
    return Vector2D(self.x+ other.x, self.y + other.y)


first = Vector2D(5, 7)
second = Vector2D(3, 9)
result = first + second

print(result.x)
print(result.y)

>>>
8
16

  • The __add__ method allows for the definition of a custom behavior for the + operator in our class.
  • it adds corresponding attributes of the objects and return a new object , containing the result

Magic Method for common operators*

__sub__ for -
__mul__ for *
__truediv__ for /
__floordiv__ for //
__mod__ for %
.......

if x hasn't implement __add__ , and x and y are of different types , then y._radd__(x) is called

>>>
class SpecialString:
  def__init__(self,cont):
     self.cont = cont


  def__truediv__(self,other):
    line = "=" * len(other,cont)
  return "\n".join([self.cont, line,other.cont)_


spam = SpecialString("spam")
hello = SpecialString("Hello World")
print(spam / hello)

>>>
spam
============
Hello world!


Magic Method for comparisons*


__It__ for <
__le__ for <=
__eq__ for ==
__ne__ for !=
.......


if __ne__ is not implemented , it returns the opposite of __eq__


>>>

class SpecialString:
  def__init__(self,cont):
     self.cont = cont


  def__gt__(self,other):
    for index in range(len(other.cont)+1):
      result = other.cont[:index] + ">" + self.cont
      result += ">" + other.cont[index:]
      print(result)

Spam = SpecialString ("Spam")
eggs = SpecialString ("eggs")
spam >eggs

.....


Magic Method for making classes act like containers*

__len__ for  len()
__getitem__ for for indexing
.......



>>>
import random

class VagueList:
  def__init__(self,cont):
    self.cont = cont

  def__getiitem__(self,index):
    return self.cont[index+random.randint(-1,1)]

 def__len__(self):
    return random.randint(0, len(self.cont)*2)

vague_list = VagueList(["A","B","C","D""E"])
print(len(vague_list ))
print(vague_list [2])

[ Objected-Oriented Programming ] Inheritance

Inheritance

  • provide a way to share functionality between classes
  • This similarity can be expressed by making them all inherit from a superclass ,which contains the shared functionality
>>>
class Animal:
  def__init__(self,name,color):
    self.name = name
    self.color = color


class Cat(Animal):
  def purr(self):
    print("Pur...")

class Dog(Animal):
  def bark(self):
    print("Woof!")


Subclass
  • a class that inherits from another class 
Superclass
  • a class that is inherited from 
Overrides
  • if a class inherits from another with the same attributes or methods , it overrides them.

>>>
class Wolf:
  def__init__(self,name,color):
    self.name = name
    self.color = color

  def bark(self):
    print("Grr....")


class Dog(Wolf):
  def bark(self):
    print("Woof!")


>>>
class A:
  def method(self):
    print("A method")

class B(A):
  def another_method(self):
    print("B method")

class C(B):
  def third_method(self):
    print("C method")

c = C()
c.method()
c.another_method()
c. third_method()

  • circular inheritance is not possible

Super function
  • useful inheritance related function that refers to the parent class
  • It can be used to find the method with certain name in an object's superclass
>>>
class A:
  def spam(self):
    print(1)

class B(A):
  def spam(self):
    print(2)
    super.spam()



  • super.spam() calls the spam method of the superclass

[ Objected-Oriented Programming ] Classes

Three paradigms of programming

  • Imperative
    • statements , loops , functions as subroutines
  • functional
    • pure functions , high-order functions , recursion
  •  Objected-Oriented Programming
    • classes , objects 

Objects are created using classes 
Class is separate from the object itself
Method is object's function

>>>
class Cat :
  def_init_(self,color,legs):
    self.color = color
    self.legs = legs


felix = Cat("ginger",4)
rover = Cat ("brown",3)


This code define a class names Cat , which has two "attributes" color and legs.



__init__
  • The __init__ method , is called when an instance(object) of the class is created,using the class name as function.
  • All method must have self as their first parameter . although it isn't explicity passed,Python  adds the self argument to the list for you .you don't need to include it when you call the methods.
  • In an __init__method , self ,attribute can therefore be used to set the initial value of an instance's attributes.
  • The __init__ method is called the class constructor

Method
  • Classes can have other method define to add functionality to them
  • All methods must have self as their first parameter

>>>
class Dog:
  def __init__ (self,name,color):
    self.name = name
    self.color = color

  def bark(self):
    print("Woof!")

fido = Dog("Fido","brown")
print_(fino.name)
fido.bark()


Class Attribute
  • are shared by all instances of the class
>>>
class Dog: 
  legs = 4
  def __init__ (self,name,color):
    self.name = name
    self.color = color

fido = Dog("Fido","brown")
print_(fino.legs)
print_(Dogs.legs)

Attribute Error (undefined Attribute , Method)


Wednesday, October 5, 2016

[ Functional Programming ] itertools

itertools => standard library

=> count
=> cycle
=> repeat

>>>
form itertools import count

for i in count(3):
    print (i)
    if i >= 11:
       break

>>>
3
4
5
6
7
8
9
10
11


=> takewhile
=> chain
=> accumulate



=> product
=> permutation

[ Functional Programming ] Sets

Sets
 => a data structures , similar to lists or dictionaries.
=> created using curly braces , or the set function
=> they can also use "in" to check whether they contain a particular item. ~ lists
=> len ~ lists
=> to create empty set , use set()


>>>
num_set = {1,2,3,4,5}
word_set = set(["a","b","c"])

print ( 3 in num_set)
print ("a" not  in word_set)

>>>
True
False

What are the difference between set and list ?
=> set , are unordered , that they can;t be indexed
=>set , cannot contain duplicate elements
=>set , instead of using append , use add
=>set , remove method removes a specific element , from set , pop removes arbitrary element

>>>
nums = {1,2,1,3,1,4,5,6}
print(nums)
nums.add(-7)
nums.remove(3)
print(nums)

>>>
{1,2,3,4,5,6}
{1,2,4,5,6,-7}


Sets can be combined using mathematical operations.
=> union
=> intersection &
=> difference
=> symmetric difference


>>>
first = {1,2,3,4,5,6}
second = {4,5,6,7,8,9}

print (first | second)
print (first & second)
print (first - second)
print (second - first)
print (first ^ second)


>>>
{1,2,3,4,5,6,7,8,9}
{4,5,6}
{1,2,3}
{7,8,9}
{1,2,3,7,8,9}

Python support data structure
 => list , dictionary , tuple , set

<dictionary>
=> need a logical association between a key:value pair
=> fast lookup for your data based on custom key
=> when your data is being constantly modified . (dictionaries are mutable)

<list>
=> if you have a collection of data that does not need random access
=> for simple , iterable , collection

<set>
=> need uniqueness for the elements

<tuples>
=> data cannot change

[ Functional Programming ] Recursion

Recursion => self-reference
factorial function

base case => a case that doesn't involve any further calls to that function

>>>
def factorial(x):
    if x ==1:  # base case
      return 1
    else:
      return x * fractorial (x-1)

print(factorial(5))


Recursion can also be indirect . One function can call a second , which calls the first , which calls the second, and so on .

>>>
def is_even(x):
    if x == 0:
      return True
    else:
      return is_odd(x-1)

def is_odd(x):
    return not is_even(x)


print(is_odd(17))
print(is_even(23))

[ Functional Programming ] Decorators * (不懂)

Decorators => provide a way to modify functions using other functions,

>>>

def decor(func):
    def wrap():  #nested function
      print("==============")
      func()
      print("==============")
    return wrap

def print_text():
    print("Hello World")

decorated = decor(print_text)
decorated()


>>>
@my_dec

>>>
my_func = my_dec(my_func)

[ Functional Programming ] Generators*

Generators => type of iterable , like lists or tuples

Unlike lists , they don't allow indexing with arbitrary indices , but that can still be iterated through with for loops.

create generators using yield statement => replacing the return of a function to provide a result to its caller without destroying local variables.

>>>
def countdown():
    i=5
    while i >0:
      yield i
      i -= 1

for i in countdown():
    print(i)

>>>
5
4
3
2
1


Due to the fact that they yield one item at a time , generators don't have the memory restrictions of lists.

>>>
def infinite_sevens();
    while True:
       yield 7'

for i in infinite_sevens():
    print(i)


Finite generators can be converted into lists by passing them as arguments to the list function

>>>
def numbers(x):
    for i in range(x):
      if i %2 ==0:
          yield i

print(list(numbers(11)))

>>>
[0.2.4.6.8.10]


generator => improved performance , lower memory usage, we don't need to wait until all the elements have been generated before we start to use them.

[ Functional Programming ] map & filter

function map => takes a function and an iterable as arguments , and returns a new iterable with the function applied to each argument.

# map
>>>
def add_five(x):
   return x+5

nums = [11,22,33,44,55]
result = list(map(add_five, nums))
print(result)

>>>
[16,27,38,49,60]


#lambda
>>>
nums = [11,22,33,44,55]  #list

result = list (map (lambda x : x+5 ,nums))
print(result)


function filter => filters an iterable by removed items that don't match a predicate (a function that returns a Boolean)

>>>
nums = [11,22,33,44,55]
res = list(filter (lambda x : x %2 ==0 , nums))
print(res)

>>>
[22,44]

[ Functional Programming ] Lambdas

Functions created using "lambda syntax" are known as "anonymous"

This approach is most commonly used when passing a simple function as an argument to another function

>>>
def my_func (f , arg)
    return f(arg)

my_func (lambda x : 2*2*2 , 5)

Lambda functions aren't as powerful as named  functions , They can only do things that require a single expression.


#named function
>>>
def polynomial(x)
    return x**2+5*x+4
print(polynimial(-4))

#lambda
>>>
print((lambda x : x**2+5*x+4) (-4))

Lambda function can be assigned to variables, and used like normal functions

>>>
double = lambda x :x*2
print(double(7))

However it is usually better to define a function with def instead .....

[ Functional Programming ] Introduction

Functional Programming => a programming style that based around functions.
Higher order functions => take function as arguments, or return them as results
"Function as object"

>>>
def apply_twice(func arg):
    return func(func(arg))

def add_five(x):
    return x +5

print (apply_twice(add_five, 10))

>>>
20


Pure Functions => have no inside effects and return a value that depends only on their arguments.

eg : Pure function
>>>
def pure_function(x,y)
    temp = z +2*y
    return temp / (2*x + y)

eg : Impure function
>>>
def impure(arg):
    some_list.append(arg)



Pure Functions
Pros

  • easier to reason about the test
  • more efficient
  • easier to run in parallel
memoization =>Once the function has been evaluated for an input , the result can be stored and referred to the next time and function of that input is needed , reducing the number of times the function is called.


Cons
  • inherently require side effects
  • more difficult to write in some situations 

Tuesday, October 4, 2016

[ More Types ] Text Analyzer

filename = input("Enter a filename : ")

with open (filename) as f:
   text = f.read()

print(text)..... ?????QQ

[ More Types ] Useful Functions


<String functions>
join
split

replace

startwith , endwith

upper
lower

<Numerical functions>
min
max
abs
sum
round ???????

<List Functions>
all
any
enumerate

[ More Types ] String Formatting

nums = [4,5,6]
msg = "Numbers : {0} {1} {2}" . format(nums[0],nums[1],nums[2])
print(msg)


a = {x},{y}.format(x=5 , y=12)
print(a)

[ More Types ] List Comprehension

cubes = [i*3 for i in range(5)]
print (cubes)

[0,1,8,27,64]

can also contain if statement

[ More Types ] List Slices

List Slices => involves indexing with "two colon -separated integers" => this returns a new list containing all the values in the old list between the indices. ~ similar to range

first number in the slice is omitted , start of the list , second number .... end
slice can also be done on tuples.

can also have third number => representing the step

negative values can be used in list slicing  , count form end. =>reverse list !!

[ More Types ] Dictionary Functions

lists , dictionary keys can be assigned to different values.

unlike lists , a new dictionary key can also be assigned a value . not just ones that already exist.

To determine whether a key is in a dictionary , you can use in and not in , just as you can for a list

A useful dictionary method is get , same as indexing , but if the key doesn't found it return None

[ More Types ] Tuples

Tuples => very similar to lists , except that they are immutable . also they are created using parentheses, rather than square brackets.

#list
 list  = [ "one" , "two" ]

#dictionary
dictionary = {1 : "one" , 2 : "two"}

#tuple
tp = ("one" , "two")

can all use nested structure

Tuples can created without the parentheses , by just separating the values with commas.

[ More Types ] Dictionaries

Dictionaries => a data structures that used to map arbitrary keys to values.
Each element in a dictionary is represented by a key : value pair.
List can be thought of as dictionaries with integer keys within a certain range

ages = {"BH" : 24 , "Lity" : 28}
print (ages ["BH"] )

A empty dictionary is defined as  {}
dictionary can store any types of data as values.
Trying to index a key that isn't part of the dictionary returns a KeyError


Only immutable object (that can't be changed) can be used as keys to dictionaries
or cause a TypeError

[ More Types ] None

None is similar to null in other language.
None object => represent the absence of  a value.

0 , [] , ""

The None object is returned by any function that doesn't explicity return anything else.

單元 13 - 文件字串

文件字串 (documentation string) 定義在模組 (module) 、函數 (function) 、類別 (class) 及方法 (method) 中,用為程式的說明文件,可用預設屬性 (attribute) __doc__ 存取


說明文件不外是解釋程式某部分的使用方式,通常會舉出簡單的例子,傳統程式語言 (programming language) 的說明文件大都是額外編寫,印成紙書或放在網路供人查詢,或是以註解 (comment) 形式加進原始程式碼 (source code) 中, Python 文件字串的特點讓程式設計師可以邊寫程式邊查文件,無須翻紙書或查網路。

我們先進入 Python 的互動式介面來看看吧!下面印出內建函數 int() 的屬性 __doc__


int() 用來建立整數物件 (object) ,因此回傳一個整數物件,這裡可以看到 int() 的解釋與用法。

下面再來看看串列 (list) 的文件字串


串列的文件字串只有簡單印出用法,大體上文件字串是依需要來設置。文件字串分成兩種,一種是單行的文件字串,另一種則是多行,下面我們用單元 8 的 big() 函數示範單行文件字串的寫法

   def big(a, b):
      """Return the bigger argument."""
      if a > b:
         return a
      else:
         return b

文件字串採用三個引號,也就是字串前後都用三個引號圍起來,單行的文件字串就是簡單的寫明函數用途

   """Return the bigger argument."""

多行的文件字串同樣用三引號字串 (triple-quoted string) ,如下例

   def big(a, b):
      """Return the bigger argument.
   
         Args: 
            a - the first one.
            b - the second one.
      """
      if a > b:
         return a
      else:
         return b

第一行同樣是函數用途,之後空一行,下面才是進一步的解釋說明,此例解釋參數 (parameter) 的用途。有沒有發現三引號字串是可以跨行的呢?是的,三引號字串可以跨行,因為三引號字串的主要用途就是當作文件字串,文件字串通常是多行的敘述。

下面我們替 class_dmeo9.py 加進模組、類別與方法的文件字串

001"""An example of the Demo class.
002
003   It demonstrates the docstring. 
004"""
005
006# This is a comment of a class.
007class Demo:
008   """A docsting of the class."""
009   # This is a comment of the method.
010   def __init__(self, v1=11, v2=22):
011      """A docsting of the __init__."""
012      self.__a = v1
013      self.__b = v2
014   
015   # This is a comment of a method.
016   def do_something(self):
017      """A docsting of a method."""
018      return self.__a + self.__b
019
020if __name__ == "__main__":
021   d = Demo(12, 34)
022   print(d.do_something())
023 
024# 檔名: class_demo10.py 
025# 作者: Kaiching Chang 
026# 時間: July, 2014

這裡僅作示範用,因此文件字串中都採取簡單的文字。

我們可以看到模組的文件字串出現在檔案的最開始,類別、方法或函數的文件字串都在關鍵字 (keyword) 的下一行,至於註解則在關鍵字的上一行,除了文件字串的位置須固定外,註解的位置是 Python 社群的習慣寫法,如果要對整個類別、方法或函數做註解,通常都會寫在關鍵字的上一行。

由於文件字串是用途及簡單例子,所以註解內容不應該與文件字串相同或相似,基本上註解的目的主要是對程式碼額外說明,至於說明內容依需要而定。

倒是不管文件字串或是註解都應按照開發團隊的習慣來走,我們這裡介紹的是官網 PEP 8 及 PEP 257 所建議的寫法。

接下來我們開發軟體的方式,帶領讀者開發 GUI 的編密碼軟體,藉此介紹更多的 Python 特性囉!

中英文術語對照


文件字串documentation string
模組module
函數function
類別class
方法method
屬性attribute
程式語言programming language
註解comment
原始程式碼source code
物件object
串列list
三引號字串triple-quoted string
參數parameter
關鍵字keyword

重點整理


  1. 文件字串用以說明模組、函數、類別及方法的功能,可用預設屬性 __doc__ 存取。
  2. 定義文件字串採用可以跨行的三引號字串,放在模組的開頭或 class 、 def 的下方第一行。


問題與討論


  1. 文件字串是什麼?為什麼要在程式中設置文件字串?
  2. 什麼是三引號字串?這跟字串有什麼不同?

練習


  1. 寫一個程式 exercise1301.py ,替 exercise1201.py 加入文件字串。
  2. 寫一個程式 exercise1302.py ,替 exercise1202.py 加入文件字串。
  3. 寫一個程式 exercise1303.py ,替 exercise1203.py 加入文件字串。

the end

單元 12 - 模組

一個 Python 檔案就是一個模組 (module) ,模組內可以定義變數 (variable) 、函數 (function) 、類別 (class) 或是任何需要的程式內容


利用關鍵字 (keyword) import ,我們可以在模組裡用其他定義好的模組內容,下例示範引入上個單元的 class_demo6.py

001import class_demo6
002
003d = Demo(12, 13)
004print(d.do_something())
005
006# 檔名: module_demo.py 
007# 作者: Kaiching Chang 
008# 時間: July, 2014

import 通常寫在程式的頭幾行,此例寫在第一行,模組名稱就是檔案名稱,接著建立 Demo 型態的變數 d ,然後印出do_something() 的回傳值 (return value) ,執行結果如下


咦?先跑出 46 ,然後是 Traceback 的敘述,這是什麼?

Traceback 是 Python 直譯器 (interpreter) 遇到無法執行的時候所提供的提示選項,這裡是說第 3 行的 Demo 沒有被定義,因而產生 NameError 的例外 (exception) 。

不是 import 了嗎?為什麼說 Demo 沒有被定義呢?這是因為 class_demo6 跟 module_demo 兩個各自的作用域 (scope) 不同, import 後要用 class_demo6 的內容必須連帶使用 class_demo6 ,這是說原本的 Demo 要改成class_demo6.Demo ,如下

001import class_demo6
002
003d = class_demo6.Demo(12, 13)
004print(d.do_something())
005
006# 檔名: module_demo2.py 
007# 作者: Kaiching Chang 
008# 時間: July, 2014

這樣執行結果就沒有問題囉


不過 46 是 class_demo6.py 的執行結果,由於 import 的機制會把引入模組中所有未縮排的程式碼都執行一次,所以執行module_demo2.py 等於會先執行 class_demo6.py 。

那我們是否應該把執行程式的模組跟放定義的模組分開來呢?大可不必,很多時候我們需要直接測試定義是否合用,因此直接放在相同檔案裡會比較方便,可是當作為其他檔案引入的時候,我們得用一套機制來區分引入跟非引入的情況,這個就得利用 Python 執行環境的預設變數 __name__ 了,當這個變數等於 "__main__" 的時候,就代表目前的模組是執行程式。

我們把 class_demo6.py 修改成 class_demo9.py ,如下

001class Demo:
002   def __init__(self, v1=11, v2=22):
003      self.__a = v1
004      self.__b = v2
005   
006   def do_something(self):
007      return self.__a + self.__b
008
009if __name__ == "__main__":
010   d = Demo(12, 34)
011   print(d.do_something())
012
013# 檔名: class_demo9.py 
014# 作者: Kaiching Chang 
015# 時間: July, 2014

我們再用以下的 module_demo3.py 引入,連帶介紹另一個關鍵字 from

001from class_demo9 import Demo
002
003d = Demo(12, 13)
004print(d.do_something())
005
006# 檔名: module_demo3.py 
007# 作者: Kaiching Chang 
008# 時間: July, 2014

第 1 行, from 加上 import 可從模組中引入指定的識別字 (identifier) 

001from class_demo9 import Demo

因此下面就可以直接使用 Demo ,無須加上模組的名稱。執行結果如下


若是在 from 、 import 後改用星號 * ,這樣表示引入所有的識別字名稱。

模組用來整理程式內容, Python 另外用套件 (package) 整理模組,好比資料夾之於檔案,不過這不在我們目前的討論範圍,接下來我們來討論可定義在模組、函數、類別或方法 (method) 中的文件字串 (documentation string) 。

中英文術語對照


模組module
變數variable
函數function
類別class
關鍵字keyword
回傳值return value
直譯器interpreter
例外exception
作用域scope
識別字identifier
套件package
方法method
文件字串documentation string

重點整理


  1. 一個 Python 檔案就是一個模組,多個模組可用套件組織管理。
  2. 若預設變數 __name__ 等於 "__main__" 的時候,表示此時這個模組為執行程式。
  3. 關鍵字 import 用來引進模組,與 from 合用則引進模組中定義的名稱,另可用星號表示引入所有名稱。


問題與討論


  1. 若甲模組中先 import 乙模組,若在程式檔案中先 import 甲模組,又 import 乙模組,這樣會發生問題嗎?
  2. 為什麼模組要設計成沒有縮排的程式碼會先被執行?

練習


  1. 寫一個程式 exercise1201.py ,替 exercise1101.py 加入 if __name__ == "__main__": 陳述。
  2. 寫一個程式 exercise1202.py ,替 exercise1102.py 加入 if __name__ == "__main__": 陳述。
  3. 寫一個程式 exercise1203.py ,替 exercise1103.py 加入 if __name__ == "__main__": 陳述。

the end

單元 11 - __init__() 方法

Python 中有一些特別的方法 (method) ,這些方法的識別字 (identifier) 前後都用兩個底線圍起來


每一種都有特定的功能,其中的 __init__() 方法就是物件 (object) 建立時所執行的方法,舉例如下

001class Demo:
002   def __init__(self, v1=11, v2=22):
003      self.__a = v1
004      self.__b = v2
005   
006   def do_something(self):
007      return self.__a + self.__b
008
009d = Demo(12, 34)
010print(d.do_something())
011 
012# 檔名: class_demo6.py 
013# 作者: Kaiching Chang 
014# 時間: July, 2014

這裡把原本的 set_att() 改成 __init__()

002def __init__(self, v1=11, v2=22):
003   self.__a = v1
004   self.__b = v2

建立 Demo 型態 (type) 的變數 (variable) d 時就像呼叫 set_att() 一樣,可以直接提供參數設定屬性 (attribute) __a 及 __b

009d = Demo(12, 34)

執行結果如下


屬性都已封裝 (encapsulate) ,如果我們還是有需要在外部程式設定屬性值的話該怎麼辦呢?這就要替每個屬性設定各自的setter 與 getter 方法了,例如

001class Demo:
002   def __init__(self, v1=11, v2=22):
003      self.__a = v1
004      self.__b = v2
005
006   def get_a(self):
007      return self.__a
008
009   def get_b(self):
010      return self.__b
011
012   def set_a(self, value):
013      self.__a = value
014
015   def set_b(self, value):
016      self.__b = value
017   
018   def do_something(self):
019      return self.__a + self.__b
020
021d = Demo(11)
022print(d.do_something())
023d.set_a(5)
024print(d.do_something())
025 
026# 檔名: class_demo7.py 
027# 作者: Kaiching Chang 
028# 時間: July, 2014

setter 是設定屬性的方法, getter 則是取得屬性的方法,上面 6 到 16 行就是定義 setter 與 getter 方法的地方,程式執行結果如下


如果是用 @property 、 @a.setter 與 @b.setter 標記 setter 與 getter 的話,程式行為就會回到預設的情況。

下面我們討論設計 __init__() 方法的技巧,同樣也適用在函數 (function) 的參數列 (parameter list) 。一個簡單的問題,參數 (parameter) 可以有預設值,這樣建立物件時無須提供參數,可是預設值不見得每一個都可以設定一樣,可是有時候我們只是想要把兩個屬性設定成相同的值說。

如果按照我們上面的設計,兩個屬性都想設定一樣的值,就變成兩個參數都得提供

   d = Demo(80, 80)

更麻煩的是如果希望兩個屬性都跟某個預設值一樣,仍然是兩個參數都得提供

   d = Demo(11, 11)

可不可以簡單一點呢?可以的,我們可以把第二個參數的預設值改成 None ,然後加入條件判斷,如下

001class Demo:
002   def __init__(self, v1=11, v2=None):
003      if v2 is None:
004         self.__a = v1
005         self.__b = v1
006      else:
007         self.__a = v1
008         self.__b = v2
009
010   def do_something(self):
011      return self.__a + self.__b
012
013d1 = Demo()
014print(d1.do_something())
015d2 = Demo(13, 12)
016print(d2.do_something())
017 
018# 檔名: class_demo8.py 
019# 作者: Kaiching Chang 
020# 時間: July, 2014

這樣的技巧在其他強型態的物件導向程式語言中被稱為多載 (overload) ,也就是函數可以定義多個參數版本,因為這些語言所有參數的型態都是固定的,如果需要不同的型態就得宣告其他參數版本的函數或方法。

None 為識別字之一,表示什麼都不是的物件。其中 __init__() 方法

002def __init__(self, v1=11, v2=None):
003   if v2 is None:
004      self.__a = v1
005      self.__b = v1
006   else:
007      self.__a = v1
008      self.__b = v2

關鍵字 is 用來判斷兩個物件是否相等,這裡為判斷第二個參數 v2 是否為 None ,如果 v2 是 None ,表示呼叫端沒有提供第二個參數,因此把兩個屬性都設定為 v1 ,反之 __a 設定成 v1 , __b 設定為 v2 。

執行結果如下


類別 (class) 的介紹到這裡先到一個段落了,由於一個 Python 檔案就是一個獨立的模組 (module) ,眾多模組集合起來就是個模組庫 (library) 了,接下來我們繼續討論模組囉!

中英文術語對照


方法method
識別字identifier
物件object
型態type
變數variable
屬性attribute
封裝encapsulate
函數function
參數列parameter list
參數parameter
多載overload
類別class
模組module
模組庫library

重點整理


  1. __init__() 方法是物件建立時所執行的方法,主要用來初始化實體屬性。
  2. 封裝是在實體屬性前加上兩個底線,這樣存取或設定實體屬性就得透過 getter 或 setter 方法。
  3. 若將 __init__() 方法其中的參數設定為 None ,便可依條件判斷來設定實體屬性值。
  4. 關鍵字 is 用來判斷兩個物件是否相等。


問題與討論


  1. 類別中自訂 __init__() 方法有什麼優點?
  2. 為什麼 Python 的屬性要預設為可以公開存取?
  3. 要怎麼替方法建立不同的參數版本?

練習


  1. 寫一個程式 exercise1101.py ,替 exercise1001.py 的 IntegerDemo 設計 __init__() 方法。
  2. 寫一個程式 exercise1102.py ,替 exercise1002.py 計算階層值的類別設計 __init__() 方法。
  3. 寫一個程式 exercise1103.py ,替 exercise1003.py 計算費氏數列的類別設計 __init__() 方法。

the end