Python小知識點(7)
阿新 • • 發佈:2018-12-13
- 類的相關介紹
""" class Human(object): phylum = 'Chordata' order = 'Primates' family = 'Human Being' ZhangSan = Human() """ # 已將該例項的屬性值重新定義,不會受到此後類屬性值變化的影響 """ ZhangSan.family = 'Mankind' print(ZhangSan.family) # Mankind # 類屬性也是可以修改的 Human.family = 'Homo' print(ZhangSan.family)# Mankind Lily = Human() print(Lily.family)# Homo ZhangSan.kingdom = 'Animalia'#例項的屬性可以直接新增,類的屬性也是如此 """ """ class Human(object): domain = 'eukarya' def __init__(self, kingdom='Animalia', phylum='Chordata', order='Primates', family='Human Being'): self.kingdom = kingdom self.phylum = phylum self.order = order self.family = family # 例項方法 # def 中都要包含self def typewrite(self): print("This is %s typing words!" %(self.family)) def add(self, n1, n2): n = n1 + n2 print(str(n1) + '+' + str(n2) + '=' + str(n)) print('You see! %s can calculate!' %(self.family)) ZhangSan = Human() LiSi = Human(kingdom='Animal', family='Homo') print(LiSi.kingdom) print(LiSi.family) print(ZhangSan.kingdom) """ """ class Human(object): domain = 'eukarya' def __init__(self, kingdom='Animalia', phylum='Chordata', order='Primates', family='Human Being'): self.kingdom = kingdom self.phylum = phylum self.order = order self.family = family def typewrite(self): print("This is %s typing words!" %(self.family)) def add(self, n1, n2): n = n1 + n2 print(str(n1) + '+' + str(n2) + '=' + str(n)) print('You see! %s can calculate!' %(self.family)) # 類方法 # 第一個引數為cls,表示類本身 # 定義類方法時,使用@classmethod 裝飾器 @classmethod def showclassmethodinfo(cls): print(cls.__name__) # __name__屬性,其值為名 print(dir(cls)) # 展示本類的所有方法 ZhangSan = Human() print(ZhangSan.showclassmethodinfo()) print(Human.showclassmethodinfo()) """ """ Human ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'add', 'domain', 'showclassmethodinfo', 'typewrite'] None Human ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'add', 'domain', 'showclassmethodinfo', 'typewrite'] None """ """ """ """ class Human(object): domain = 'eukarya' # 類屬性(可通過類名,例項訪問) def __init__(self, kingdom='Animalia', phylum='Chordata', order='Primates', family='Human Being'): self.kingdom = kingdom # 例項屬性(只能通過例項訪問) self.phylum = phylum self.order = order self.family = family def typewrite(self): print("This is %s typing words!" %(self.family)) def add(self, n1, n2): n = n1 + n2 print(str(n1) + '+' + str(n2) + '=' + str(n)) print('You see! %s can calculate!' %(self.family)) @classmethod def showclassmethodinfo(cls): print(cls.__name__) print(dir(cls)) # 靜態方法 # 無引數 # 定義類方法時,使用@staticmethod 裝飾器 @staticmethod def showclassattributeinfo(): print(Human.__dict__) # __dict__屬性,返回鍵名為屬性名,鍵值為屬性值的字典 # 雙下劃線前後綴的屬性為自帶的特殊的類屬性 ZhangSan = Human() print(ZhangSan.showclassattributeinfo()) print(Human.showclassattributeinfo()) """ class Human(object): domain = 'eukarya' # 類屬性(可通過類名,例項訪問) def __init__(self, kingdom='Animalia', phylum='Chordata', order='Primates', family='Human Being'): self.kingdom = kingdom # 例項屬性(只能通過例項訪問) self.phylum = phylum self.__order = order # 私有屬性 self.family = family def typewrite(self): print("This is %s typing words!" %(self.family)) def add(self, n1, n2): n = n1 + n2 print(str(n1) + '+' + str(n2) + '=' + str(n)) print('You see! %s can calculate!' %(self.family)) @classmethod def showclassmethodinfo(cls): print(cls.__name__) print(dir(cls)) @staticmethod def showclassattributeinfo(): print(Human.__dict__) """ ZhangSan = Human() print(ZhangSan._Human__order) # Primates print(ZhangSan.order) #與ZhanSan.__order結果相同,錯誤 """ # 隱式繼承 # 完全繼承所有成員 # 隱式繼承中,父類的私有成員不能繼承 # 如果在子類中使用__init__來構造例項屬性時,一定要用super函式去初始化父類 class Male(Human): def __init__(self, gender='male'): super(Male, self).__init__()# super函式的第一個引數是父類的名字 self.gender = gender def add(self, n1, n2): # 在子類中重新定義add方法 n = n1 - n2 print(str(n1) + '-' + str(n2) + '=' + str(n)) print('You see! %s can NOT use addition!' %(self.gender)) someoneismale = Male() print(someoneismale.family)# Human Being print(someoneismale.kingdom)# Animalia print(someoneismale.add(1, 1)) # 父類的例項與子類不是同一個型別 # 子類的例項與父類是同類 # 繼承與同一個父類的子類是不同類 # 呼叫物件的add方法 def addition(obj, n1, n2): obj.add(n1, n2) addition(someoneismale, 1, 1) addition(Male(), 1, 1)
- 說明文件格式
def remove(self, item):
"""
Precondition: item is in self. 先驗條件(只有該語句為真的時候,方法才能夠正確地執行操作)
Raises: KeyError if item in not in self. 用來說明可能發生的異常,通常是無法滿足方法的先驗條件而導致的結果
Postcondition: item is removed from self. 後驗條件(當方法執行完畢後,變為了什麼情況)
"""
- 解包
>>> a, b, c = "jkl" >>> a 'j' >>> b 'k' >>> c 'l' >>> a, b, c = ['j', 'k', (1, 2, 3)] >>> a 'j' >>> b 'k' >>> c (1, 2, 3) >>> record = ('Dave', '
[email protected]', '773-555-1212', '847-555-1212') >>> name, email, *phone_numbers = record >>> name 'Dave' >>> email '[email protected]' >>> phone_numbers ['773-555-1212', '847-555-1212'] >>> *trailing, current = [10, 8, 7, 1, 9, 5, 10, 3] >>> trailing [10, 8, 7, 1, 9, 5, 10] >>> current 3 >>> record = ('ACME', 50, 123.45, (12, 18, 2012)) >>> name, *_, (*_, year) = record >>> name 'ACME' >>> year 2012
- 堆
from collections import deque
q = deque(maxlen=3)
q.append(3)
q.appendleft(3)
q.pop()
q.popleft()
>>> import heapq
>>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
>>> print(heapq.nlargest(2, nums))
[42, 37]
>>> print(heapq.nsmallest(2, nums))
[-4, 1]
import heapq
portfolio = [
{'name':'IBM', 'shares':100, 'price':91.1},
{'name':'AAPL', 'shares':50, 'price':543.22},
{'name':'FB', 'shares':200, 'price':21.09},
{'name':'HPQ', 'shares':35, 'price':31.75},
{'name':'YHOO', 'shares':45, 'price':16.35},
{'name':'ACME', 'shares':75, 'price':115.65}
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
print(cheap, '\n', expensive)
"""
[{'shares': 45, 'name': 'YHOO', 'price': 16.35}, {'shares': 200, 'name': 'FB', 'price': 21.09}, {'shares': 35, 'name': 'HPQ', 'price': 31.75}]
[{'shares': 50, 'name': 'AAPL', 'price': 543.22}, {'shares': 75, 'name': 'ACME', 'price': 115.65}, {'shares': 100, 'name': 'IBM', 'price': 91.1}]
"""
# 優先順序佇列的實現
import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]
# 如何使用
class Item:
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Item({!r})'.format(self.name)
q= PriorityQueue()
q.push(Item('foo'), 1)
q.push(Item('bar'), 5)
q.push(Item('spam'), 4)
q.push(Item('grok'), 1)
for i in range(4):
print(q.pop())
"""
Item('bar')
Item('spam')
Item('foo')
Item('grok')
"""
- 特殊變數
_xxx 不能用 from module import* 匯入 xxx 系統定義名字 __xxx 類中私有變數名