python 簡單定製

2021-09-17 18:31:07 字數 2532 閱讀 8975

基本要求:

– 定製乙個計時器的類

– start和stop方法代表啟動計時和停止計時

– 假設計時器物件t1,print(t1)和直接呼叫t1均顯示結果

– 當計時器未啟動或已經停止計時,呼叫stop方法會給予溫馨的提示

– 兩個計時器物件可以進行相加:t1 + t2

– 只能使用提供的有限資源完成

你需要使用這些資源:

str魔法方法的使用:

#__str__使用:被列印的時候需要以字串的形式輸出的時候,

就會找到這個方法,並將返回值列印出來

>>> class a():

def __str__(self):

return "小甲魚是帥哥"

>>> a=a()

>>> a

<__main__.a object at 0x00000233f611ac88>

>>> print(a)

小甲魚是帥哥

repr魔法方法的使用:

#返回乙個物件的可列印字串

>>> class b():

def __repr__(self):

return "小甲魚是帥哥"

>>> b=b()

>>> b

小甲魚是帥哥

>>>

計時器的類:

import time as t

class mytimer():

def start(self):

self.start = t.localtime()

print("計時開始...")

def stop(self):

self.stop = t.localtime()

self._calc()

print("計時結束...")

def _calc(self):

self.lasted =

self.prompt="總共執行了"

for index in range(6):

self.prompt += str(self.lasted[index])

print(self.prompt)

執行結果:

>>> t1 = mytimer()

>>> t1.start()

計時開始...

>>> t1.stop()

總共執行了000006

計時結束...

改良版:

import time as t

class mytimer():

def __init__(self):

self.unit = ['年','月','天','小時','分鐘','秒']

self.prompt = '未開始計時!'

self.lasted =

self.begin = 0

self.end = 0

def __repr__(self):

return self.prompt

def __add__(self,other):

prompt="總共執行了"

result =

for index in range(6):

if result[index]:

prompt += (str(result[index]) + self.unit[index])

return prompt ######

def start(self):

self.begin = t.localtime()

print("計時開始...")

def stop(self):

if not self.begin:

else:

self.end = t.localtime()

self._calc()

print("計時結束...")

def _calc(self):

self.lasted =

self.prompt="總共執行了"

for index in range(6):

if self.lasted[index]:

self.prompt += (str(self.lasted[index]) + self.unit[index])

self.begin = 0 #######

self.end = 0

上面小甲魚的方案還有可以改進的地方:

如果開始計時的時間是(2023年2月22日16:30:30),停止時間是(2023年1月23日15:30:30),那按照小甲魚方法的計算方式會得到結果(3年-1月1天-1小時),對此我們應該做一些轉換。

現在計算機的執行速度都非常快,而這裡程式的最小計算單位是秒,精度上遠遠不足。

python定製 python中定製類

1 python中 str 和repr 如果要把乙個類的例項變成 str,就需要實現特殊方法 str classperson object def init self,name,gender self.name name self.gender genderdef str self return p...

Python學習 簡單定製定時器

time模組可參考 簡單示例 import time as t class mytimer 初始化 def init self self.unit 年 月 天 小時 分鐘 秒 self.prompt 計時還未開始t t self.lasted self.begin 0 self.end 0def s...

Python 定製序列

1 python中的三大容器 列表list,元組tuple,字串string 2 python允許我們定製乙個不可變的容器,如string,中就不能有修改容器的資料方法,如 setitem delitem 3 如果希望定製的容器支援reversed 內建函式,則容器中需定義 reversed 方法,...