# 1.定義一個數學中的復數類 Complex,它有一個構造函數與一個顯示函數,建立一個 Complex 對象并調用該顯示函數顯示。
class Complex:
def __init__(self, a):
self.a = a
def display(self):
print(self.a)
com = Complex("aaa")
com.display()
# 2.定義一個計算機類 MyComputer,它包含 CPU 類型(String 類型)、RAM 內存大小(Integer 類型)、HD 硬盤大小(Integer 類型),
# 設計它的構造函數,并設計一個顯示函數,建立一個 MyComputer 對象并調用該顯示函數顯示。
class MyComputer:
def __init__(self, CPU, RAM, HD):
self.CPU = CPU
self.RAM = RAM
self.HD = HD
def show(self):
str1 = "cpu是{},RAM 內存大小是{}G,HD 硬盤大小是{}G".format(self.CPU, self.RAM, self.HD)
print(str1)
cpu = "8核32線程"
RAM = 8
HD = 500
mc = MyComputer(cpu, RAM, HD)
mc.show()
# 3.設計一個整數類 MyInteger,它有一個整數變量,并有一個 Value 屬性,可以通過為 Value 存取該變量的值,
# 還有一個轉二進制字符串的成員函數 toBin 及轉十六進制字符串的成員函 數 toHex。
class MyInteger:
def __init__(self, num):
self.num = num
def Value(self):
print(self.num)
def toBin(self):
print("轉換為二進制為:", bin(self.num))
def toHex(self):
print("轉換為十六進制為:", hex(self.num))
def tootc(self):
print("轉換為八進制為:", oct(self.num))
num = 789
mi = MyInteger(num)
mi.Value()
mi.toBin()
mi.toHex()
mi.tootc()
# 4. 建立一個普通人員類 Person,包含姓名(m_name)、性別(m_sex)、年齡(m_age)成員變量。
# (1) 建立 Person 類,包含 Private 成員 m_name、m_sex、m_age 成員變量;
# (2) 建立 Person 的構造函數;
# (3) 建立一個顯示過程 Show(),顯示該對象的數據;
# (4) 派生一個學生類 Student,增加班級(m_class),專業(yè)(m_major),設計這些類的構造函 數;
# (5) 建立 m_class、m_major 對應的屬性函數 sClass()、sMajor();
# (6) 建立顯示成員函數 Show(),顯示該學生對象所有成員數據;
class Person:
def __init__(self, m_name, m_sex, m_age):
self.__m_name = m_name
self.__m_sex = m_sex
self.__m_age = m_age
def Show(self):
print(self.__m_name, self.__m_sex, self.__m_age,end=" ")
class Student(Person):
def __init__(self, m_name, m_sex, m_age, m_class, m_major):
# Person.__init__(self, m_name, m_sex, m_age) # 普通方法調用
super(Student,self).__init__(m_name, m_sex, m_age) # 使用super方法調用父類 ——__init__
self.__m_class, self.__m_major = m_class, m_major
def sClass(self):
print(self.__m_class)
def sMajor(self):
print(self.__m_major)
def Show(self):
# Person.Show(self) # 普通方法調用
super(Student, self).Show() # 使用super方法調用父類 —— Show方法
print(self.__m_class, self.__m_major)
stu = Student("張三", "男", "18", "高三", "理科")
stu.Show()
# 5. 建立一個時間類 Time,它包含時 hour,分 minute,秒 second 的實例屬性
# (1) 設計時間顯示函數 show(self);
# (2) 設計兩個時間大小比較函數 compare(self,t),其中 t 是另外一個時間;
class Time:
def __init__(self,hour, minute, second):
self.hour = hour
self.minute = minute
self.second = second
def show(self):
format_time = "{}:{}:{}".format(self.hour,self.minute,self.second)
print(format_time)
def compare(self):
t = "23:45:07"
t_time = t.split(":")
t_hour = t_time[0]
t_minute = t_time[1]
t_second = t_time[2]
t_seconds = int(t_hour) * 3600 + int(t_minute) * 60 + int(t_second)
compare_sec = abs(t_seconds - (self.hour*3600 + self.minute*60 +self.second))
compare_hour = compare_sec//3600
compare_minute = (compare_sec%3600)//60
compare_second = (compare_sec%3600)%60
print("{}:{}:{}".format(compare_hour,compare_minute,compare_second))
time = Time(12, 30, 1)
time.show()
time.compare()

前行.png