高見龍

iOS app/Ruby/Rails Developer & Instructor, 喜愛非主流的新玩具 :)

物件導向程式設計

建立類別(Class)

類別命名建議:首字大寫

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class ClassA(object):
  def __init__(self):
    print "Hello Python!"

  def __del__(self):
    print "Goodbye Python!"

  def __str__(self):
    return "This is Class A"

  def say_hello(self, words):
    print "Hello,", words

  def do_nothing(self):
    pass

a = ClassA()
a.say_hello("eddie")
print a

# 執行結果
Hello Python!
Hello, eddie
This is Class A
Goodbye Python!

其中,__init__就是會在物件被建立出來的時候被呼叫的程式碼,而__del__則是物件用完被回收時候執行的程式碼。

private method

Python的類別裡,所有的方法預設都是public的,但有些時候,有些method你就是不想讓隨便就被拿到,在別的程式語言會有publicprotectedprivate之類的method修飾詞來設定,不過Python沒有這樣的東西,而是使用2個底線

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class ClassB(object):
  def __private_method(self):
    print "this is for personal only"

  def get_private_method(self):
    self.__private_method()

b = ClassB()

b.__private_method()
# 執行結果
# AttributeError: 'ClassB' object has no attribute '__private_method'

b.get_private_method()
# 執行結果
# this is for personal only

繼承

1
2
3
4
5
6
7
8
9
class FatherClass(object):
  def say_hello(self, words):
    print "Hello,", words

class SonClass(FatherClass):
  pass

son = SonClass()
son.say_hello("Python")

可多重繼承,但若父類別同時有同名之method,需注意多重繼承之順序

1
2
3
4
5
6
7
8
9
10
11
12
class FatherClass(object):
  def say_hello(self, words):
      print "Hello,", words

class MotherClass(object):
  pass

class SonClass(FatherClass, MotherClass):
  pass

son = SonClass()
son.say_hello("Python")

更多精彩內容,請見官網文件:http://docs.python.org/tutorial/classes.html

Comments