国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python中有趣在__call__函數

2020-02-23 01:37:13
字體:
來源:轉載
供稿:網友

Python中有一個有趣的語法,只要定義類型的時候,實現__call__函數,這個類型就成為可調用的。
換句話說,我們可以把這個類型的對象當作函數來使用,相當于 重載了括號運算符。

class g_dpm(object):def __init__(self, g):self.g = gdef __call__(self, t):return (self.g*t**2)/2

計算地球場景的時候,我們就可以令e_dpm = g_dpm(9.8),s = e_dpm(t)。

class Animal(object):  def __init__(self, name, legs):    self.name = name    self.legs = legs    self.stomach = []       def __call__(self,food):    self.stomach.append(food)   def poop(self):    if len(self.stomach) > 0:      return self.stomach.pop(0)   def __str__(self):        return 'A animal named %s' % (self.name)     cow = Animal('king', 4) #We make a cowdog = Animal('flopp', 4) #We can make many animalsprint 'We have 2 animales a cow name %s and dog named %s,both have %s legs' % (cow.name, dog.name, cow.legs)print cow #here __str__ metod work #We give food to cowcow('gras')print cow.stomach #We give food to dogdog('bone')dog('beef')print dog.stomach #What comes inn most come outprint cow.poop()print cow.stomach #Empty stomach '''-->outputWe have 2 animales a cow name king and dog named flopp,both have 4 legsA animal named king['gras']['bone', 'beef']gras[]'''

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 新巴尔虎左旗| 葫芦岛市| 大渡口区| 晋中市| 水城县| 永州市| 徐水县| 乌拉特后旗| 博客| 肥西县| 会东县| 灌阳县| 永福县| 镶黄旗| 山东| 论坛| 廉江市| 白朗县| 比如县| 东莞市| 牡丹江市| 视频| 承德市| 昌乐县| 安龙县| 长海县| 辰溪县| 新野县| 神木县| 岐山县| 凭祥市| 乐昌市| 南昌市| 中卫市| 会理县| 滦平县| 常州市| 即墨市| 仁化县| 宜丰县| 即墨市|