Python 物件導向程式設計入門
George Boorman
Curriculum Manager, DataCamp
selfself.___ 參照屬性class MyClass: # function definition in class # first argument is self def my_method1(self, other_args...): # do things heredef my_method2(self, my_attr): # attribute created by assignment self.my_attr = my_attr ...
__init__() 方法__methodname__ 語法而自動呼叫class Customer:
def __init__(self, name):
# 建立 .name 屬性並設為參數 name
self.name = name
print("The __init__ method was called")
# __init__ 會被隱式呼叫
cust = Customer("Lara de Silva")
print(cust.name)
The __init__ method was called
Lara de Silva
class MyClass: def my_method1(self, attr1): self.attr1 = attr1 ... def my_method2(self, attr2): self.attr2 = attr2 ...obj = MyClass() # 建立 attr1 obj.my_method1(val1) # 建立 attr2 obj.my_method2(val2)
class MyClass: def __init__(self, attr1, attr2): self.attr1 = attr1 self.attr2 = attr2 ...# 一次建立所有屬性 obj = MyClass(val1, val2)
class Customer: # 加入 balance 引數 def __init__(self, name, balance):self.name = name # 加入 balance 屬性 self.balance = balance print("The __init__ method was called")
# __init__ 被呼叫
cust = Customer("Lara de Silva", 1000)
print(cust.name)
print(cust.balance)
The __init__ method was called
Lara de Silva
1000
class Customer:
# 為 balance 設定預設值
def __init__(self, name, balance=0):
self.name = name
# 指定新屬性
self.balance = balance
print("The __init__ method was called")
# 不需明確指定 balance cust = Customer("Lara de Silva")print(cust.name) # balance 屬性仍會被建立 print(cust.balance)
The __init__ method was called
Lara de Silva
0
__init__() 初始化屬性__init__() 初始化屬性類別用 CamelCase,函式與屬性用 lower_snake_case
__init__() 初始化屬性類別用 CamelCase,函式與屬性用 lower_snake_case
self 為 selfclass MyClass:
# 這樣可行,但不建議
def my_method(george, attr):
george.attr = attr
__init__() 初始化屬性類別用 CamelCase,函式與屬性用 lower_snake_case
self 就是 selfclass MyClass:
"""This class does nothing"""
pass
Python 物件導向程式設計入門