# 高級特性

## 類設計中的核心語法

``````>>> var1 = 'Hello'
>>> var2 = ' World!'
>>> var1 + var2
'Hello World!'
>>>
'Hello World!'
>>> num1 = 45
>>> num2 = 60
105
>>> var3 = ['a', 'b']
>>> var4 = ['hello', ' John']
['a', 'b', 'hello', ' John']``````

``````class SumList(object):
def __init__(self, my_list):
self.mylist = my_list
new_list = [ x + y for x, y in zip(self.mylist, other.mylist)]

return SumList(new_list)

def __repr__(self):
return str(self.mylist)

aa = SumList([3,6, 9, 12, 15])

bb = SumList([100, 200, 300, 400, 500])
cc = aa + bb # aa.__add__(bb)
print(cc) # should gives us a list ([103, 206, 309, 412, 515])``````

``[103, 206, 309, 412, 515]``

``````'abc' in var # var.__contains__('abc')
var == 'abc' # var.__eq__('abc')
var[1] # var.__getitem__(1)
var[1:3] # var.__getslice__(1, 3)
len(var) # var.__len__()
print(var) # var.__repr__()``````

## 繼承自內置的類型

``````class MyDict(dict):

def __setitem__(self, key, val):
print('setting a key and value!')
dict.__setitem__(self, key, val)

dd = MyDict()
dd['a'] = 10
dd['b'] = 20

for key in dd.keys():
print('{0} = {1}'.format(key, dd[key]))``````

``````setting a key and value!
setting a key and value!
a = 10
b = 20``````

``````# Mylist inherits from 'list' object but indexes from 1 instead for 0!
class Mylist(list): # inherits from list
def __getitem__(self, index):
if index == 0:
raise IndexError
if index > 0:
index = index - 1
return list.__getitem__(self, index) # this method is called when

# we access a value with subscript like x[1]
def __setitem__(self, index, value):
if index == 0:
raise IndexError
if index > 0:
index = index - 1
list.__setitem__(self, index, value)

x = Mylist(['a', 'b', 'c']) # __init__() inherited from builtin list

print(x) # __repr__() inherited from builtin list

x.append('HELLO'); # append() inherited from builtin list

print(x[1]) # 'a' (Mylist.__getitem__ cutomizes list superclass
# method. index is 1, but reflects 0!

print (x[4]) # 'HELLO' (index is 4 but reflects 3!``````

``````['a', 'b', 'c']
a
HELLO``````

## 命名約定

PEP代表Python增強提議，並且是一系列在Python社區中分發以討論提議的更改的文檔。 例如，建議所有人，

• 模塊名稱 - all_lower_case
• 類名稱和異常名稱 - CamelCase
• 全局和本地名稱 - all_lower_case
• 函數和方法名稱 - all_lower_case
• 常量 - ALL_UPPER_CASE

## 爲什麼遵守慣例？

• 對絕大多數開發人員更熟悉。
• 大多數讀者更閱讀代碼。
• 將匹配在相同代碼庫上工作的其他貢獻者的風格。
• 註解是一名專業軟件開發人員必要的工作。
• 每個人都會接受。

## 變量命名 - ‘公共’和’私人’

• 公共屬性或變量(打算由此模塊的導入者或此類的用戶使用)- `regular_lower_case`
• 私有屬性或變量(由模塊或類內部使用)- `_single_leading_underscore`
• 不應被子類化的私有屬性 - `__ double_leading_underscore`
• 魔術屬性 - `__ double_underscores __`(使用它們，不要創建它們)
``````class GetSet(object):

instance_count = 0 # public

__mangled_name = 'no privacy!' # special variable

def __init__(self, value):
self._attrval = value # _attrval is for internal use only
GetSet.instance_count += 1

@property
def var(self):
print('Getting the "var" attribute')
return self._attrval

@var.setter
def var(self, value):
print('setting the "var" attribute')
self._attrval = value

@var.deleter
def var(self):
print('deleting the "var" attribute')
self._attrval = None

cc = GetSet(5)
cc.var = 10 # public name
print(cc._attrval)
print(cc._GetSet__mangled_name)``````

``````setting the "var" attribute
10
no privacy!``````