iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 20
0
自我挑戰組

30天學會Python系列 第 20

Python - Class類別(1)

  • 分享至 

  • twitterImage
  •  

什麼是物件?

Python身為物件導向語言(object-oriented),在Python中任何東西都是一個物件(object),例如之前介紹過的數字、字串或是列表,都是在Python中定義的物件,物件裡面有:

  • 資料 (稱為屬性attribute)
  • 程式碼 (稱為方法method)

例如整數8,就是一個值為8且可以使用加法與乘法的整數物件,而當你要建立一個全新的物件時,必須先定義一個類別(class)來說明裡面有些什麼,一個類別實例化之後稱為物件,那又如何定義類別呢?

類別定義 Class Definition Syntax

class ClassName:    
    <statement-1>    
    .    
    .    
    .    
    <statement-N>

類別物件 Class Object

支援兩種操作:

  • 屬性引用
  • 實例化 instantiation (instance)

屬性引用

其中 MyClass.i 及 MyClass.f 都是有效的屬性引用

class MyClass:    
    """A simple example class"""    
    i = 12345    
    def f(self):        
        return 'hello world'

MyClass.i
MyClass.f

實例化

回傳一個類的實例物件

x = MyClass()

實例化操作的初始化:定義 init() 函數
而這個函數在物件被生成時執行,類似 C++ 中 Class 的 Contructor

class Complex:    
    def __init__(self, realpart, imagpart):
        self.r = realpart        
        self.i = imagpart
        
x = Complex(3.0, -4.5)
x.r, x.ic

類變數及實例變數

class Dog:
    kind = 'canine'         # class variable shared by all instances
    def __init__(self, name):
        self.name = name    # instance variable unique to each instance


d = Dog('Fido')
e = Dog('Buddy')
d.kind                  # shared by all dogs'canine'
e.kind                  # shared by all dogs'canine'
d.name                  # unique to d'Fido'
e.name                  # unique to e'Buddy'

上一篇
Python - Function(3)
下一篇
Python - Class類別(2) - 封裝Encapsulation
系列文
30天學會Python30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言