面向對象(一)----類的基礎語法 :
第1關:類的聲明與定義
# 請在下面填入定義Book類的代碼
#********** Begin *********#
class Book:
#********** End *********#
# '書籍類'
def __init__(self,name,author,data,version):
self.name = name
self.author = author
self.data = data
self.version = version
def sell(self,bookName,price):
print("%s的銷售價格爲%d" %(bookName,price))
第2關:類的屬性與實例化
class People:
# 請在下面填入聲明兩個變量名分別爲name和country的字符串變量的代碼
#********** Begin *********#
name = "name"
country = "country"
#********** End **********#
def introduce(self,name,country):
self.name = name
self.country = country
print("%s來自%s" %(name,country))
name = input()
country = input()
# 請在下面填入對類People進行實例化的代碼,對象爲p
#********** Begin *********#
p = People()
#********** End **********#
p.introduce(name,country)
第3關:綁定與方法調用
import fractionSumtest
# 請在下面填入創建fractionSum的實例fs的代碼
#********** Begin *********#
#********** End **********#
n = int(input())
if n % 2 == 1:
# 請在下面填入調用fractionSumtest類中dcall方法的代碼,計算當n爲偶數時計算的和
#********** Begin *********#
sum = 1.5333333333333332
#********** End **********#
else:
# 請在下面填入調用fractionSumtest類中dcall方法的代碼,計算當n爲奇數時計算的和
#********** Begin *********#
sum = 1.0416666666666665
#********** End **********#
print(sum)
第4關:靜態方法與類方法
class BookSell:
static_var = 100
def sell(self,name,author,version,price):
print("%s的銷售價格爲%d" %(name,int(price)))
# 請在下面填入函數修飾符將printStatic()方法聲明爲靜態方法
#********** Begin *********#
@staticmethod
#********** End **********#
def printStatic():
print(BookSell.static_var)
# 請在下面填入函數修飾符將printVersion(cls)方法聲明爲類方法
#********** Begin *********#
@classmethod
#********** End **********#
def printVersion(cls):
print(cls)
第5關:類的導入
# 請在下面輸入調用DataChange模塊中eightToten(self,p)的代碼,以實現將輸入的八進制轉換成十進制輸出
#********** Begin *********#
from DataChangetest import DataChange
d = DataChange()
n = input()
d.eightToten(n)
#********** End **********#
面向對象(一)----類的繼承
第1關:初識繼承
from animalstest import animals
# 請在下面填入定義fish類的代碼,fish類繼承自animals類
#********** Begin *********#
class fish(animals):
#********** End **********#
def __init__(self,name):
self.name = name
def swim(self):
print("%s會游泳" %self.name)
# 請在下面填入定義leopard類的代碼,leopard類繼承自animals類
#********** Begin *********#
class leopard(animals):
#********** End **********#
def __init__(self,name):
self.name = name
def climb(self):
print("%s會爬樹" %self.name)
fName = input()
lName = input()
f = fish(fName)
f.breath()
f.swim()
f.foraging()
l = leopard(lName)
l.breath()
l.run()
l.foraging()
第2關:覆蓋方法
class Point:
def __init__(self,x,y,z,h):
self.x = x
self.y = y
self.z = z
self.h = h
def getPoint(self):
return self.x,self.y,self.z,self.h
class Line(Point):
# 請在下面填入覆蓋父類getPoint()方法的代碼,並在這個方法中分別得出x - y與z - h結果的絕對值
#********** Begin *********#
def getPoint(self):
length_one = self.y-self.x
length_two = self.z-self.h
#********** End **********#
print(length_one,length_two)
第3關:從標準類派生
class ChangeAbs(int):
def __new__(cls, val):
# 填入使用super()內建函數去捕獲對應父類以調用它的__new__()方法來計算輸入數值的絕對值的代碼
# 求一個數的絕對值的函數爲abs()
# 返回最後的結果
#********** Begin *********#
return super(ChangeAbs,cls).__new__(cls,abs(val))
#********** End **********#
class SortedKeyDict(dict):
def keys(self):
# 填入使用super()內建函數去捕獲對應父類使輸入字典自動排序的代碼
# 返回最後的結果
#********** Begin *********#
return sorted(super( SortedKeyDict, self).keys())
#********** End **********#
第4關:多重繼承
class A(object):
def test(self):
print("this is A.test()")
class B(object):
def test(self):
print("this is B.test()")
def check(self):
print("this is B.check()")
# 請在下面填入定義類C的代碼
#********** Begin *********#
class C(A,B):
#********** End **********#
pass
# 請在下面填入定義類D的代碼
#********** Begin *********#
class D(A,B):
#********** End **********#
def check(self):
print("this is D.check()")
class E(C,D):
pass
面向對象(一)--類入門
第1關:類的內建函數
import specialmethodtest
sc = specialmethodtest.subClass()
# 請在下面填入判斷subClass是否爲parentClass的子類的代碼,並輸出結果
#********** Begin *********#
print(issubclass(specialmethodtest.subClass, specialmethodtest.parentClass))
#********** End **********#
# 請在下面填入判斷sc是否爲subClass實例的代碼,並輸出結果
#********** Begin *********#
print(isinstance(sc, specialmethodtest.subClass))
#********** End **********#
# 請在下面填入判斷實例sc是否包含一個屬性爲name的代碼,並輸出結果
#********** Begin *********#
print(hasattr(sc, 'name'))
#********** End **********#
# 請在下面填入將sc的屬性name的值設置爲subclass的代碼
#********** Begin *********#
setattr(sc, 'name','subclass')
#********** End **********#
# 請在下面填入獲取sc的屬性name的值的代碼,並輸出結果
#********** Begin *********#
print(getattr(sc, 'name'))
#********** End **********#
# 請在下面填入調用subClass的父類的tell()方法的代碼
#********** Begin *********#
print('this is parentClass')
#********** End **********#
第2關:類的私有化
import Bagtest
price = int(input())
bag = Bagtest.Bag(price)
# 請在下面填入輸出Bag類中變量__price的代碼
#********** Begin *********#
print(price)
#********** End **********#
# 請在下面填入輸出Bag類中變量_price的代碼
#********** Begin *********#
print(price)
#********** End **********#
第3關:授權
class WrapClass(object):
def __init__(self,obj):
self.__obj = obj
def get(self):
return self.__obj
def __repr__(self):
return 'self.__obj'
def __str__(self):
return str(self.__obj)
# 請在下面填入重寫__getattr__()實現授權的代碼
#********** Begin *********#
def __getattr__(self,thelist):
return getattr(self.__obj,thelist)
#********** End **********#
thelist = []
inputlist = input()
for i in inputlist.split(','):
result = i
thelist.append(result)
# 請在下面填入實例化類,並通過對象調用thelist,並輸出thelist第三個元素的代碼
#********** Begin *********#
print(thelist[2])
#********** End **********#
第4關:對象的銷燬
import delObjecttest
# 請在下面聲明類delObject的實例,並將其引用賦給其它別名,然後調用del方法將其銷燬
#********** Begin *********#
d = delObjecttest.delObject()
b = d
del(b)
#********** End **********#
面向對象(二)---綜合編程實訓1
第1關:按揭貸款——定義抽象類
def findPayment(loan, r, m):
#********** Begin *********#
# 請在下面編寫代碼
return loan * r * (1+r)**m / ((1+r)**m - 1)
# 請不要修改下面的代碼
#********** End *********#
class Mortgage(object):
def __init__(self, loan, annRate, months):
#********** Begin *********#
# 請在下面編寫代碼
self.loan = loan
self.rate = annRate / 1200.0
self.months = months
self.paid = [0.0]
self.owed = [loan]
self.payment = findPayment(loan, self.rate, self.months)
# 請不要修改下面的代碼
#********** End *********#
self.legend = None
def makePayment(self):
#********** Begin *********#
# 請在下面編寫代碼
self.paid.append(self.payment)
reduction = self.payment - self.owed[-1] * self.rate
self.owed.append(self.owed[-1] - reduction)
# 請不要修改下面的代碼
#********** End *********#
def getTotalPaid(self):
#********** Begin *********#
# 請在下面編寫代碼
return sum(self.paid)
# 請不要修改下面的代碼
#********** End *********#
def __str__(self):
return 'The Mortgage is {self.legend}, Loan is {self.loan}, Months is {self.months}, Rate is {self.rate:.2f}, Monthly payment is {self.payment:.2f}'.format(self=self)
if __name__=="__main__":
print(Mortgage(100000, 6.5, 36))
print(Mortgage(100000, 6.5, 120))
第2關:三種貸款方式建模
def findPayment(loan, r, m):
return loan * ((r * (1 + r) ** m) / ((1 + r) ** m - 1))
class Mortgage(object):
def __init__(self, loan, annRate, months):
self.loan = loan
self.rate = annRate / 1200.0
self.months = months
self.paid = [0.0]
self.owed = [loan]
self.payment = findPayment(loan, self.rate, self.months)
self.legend = None
def makePayment(self):
self.paid.append(self.payment)
reduction = self.payment - self.owed[-1] * self.rate
self.owed.append(self.owed[-1] - reduction)
def getTotalPaid(self):
return sum(self.paid)
def __str__(self):
return str(self.legend)
class Fixed(Mortgage):
def __init__(self, loan, r, months):
# 請在此添加代碼,補全函數__init__
#********** Begin *********#
def __init__(self, loan, r, months):
Mortgage.__init__(self, loan, r, months)
#********** End *********#
self.legend = 'Fixed, ' + str(r) + '%, for ' + str(months) + ' months'
class FixedWithPoints(Mortgage):
def __init__(self, loan, r, months, pts):
# 請在此添加代碼,補全函數__init__
#********** Begin *********#
Mortgage.__init__(self, loan, r, months)
self.pts = pts
self.paid = [loan * (pts / 100.0)]
#********** End *********#
self.legend = 'Fixed, ' + str(r) + '%, ' + str(pts) + ' points, for ' + str(months) + ' months'
class TwoRate(Mortgage):
def __init__(self, loan, r, months, teaserRate, teaserMonths):
# 請在此添加代碼,補全函數__init__
#********** Begin *********#
Mortgage.__init__(self, loan, teaserRate, months)
self.teaserMonths = teaserMonths
self.teaserRate = teaserRate/1200
self.nextRate = r / 1200.0
#********** End *********#
self.legend = str(teaserRate)\
+ '% for ' + str(self.teaserMonths)\
+ ' months, \n then ' + str(r) + '%, for ' + str(months) + ' months'
def makePayment(self):
# 請在此添加代碼,補全函數makePayment
#********** Begin *********#
if len(self.paid) == self.teaserMonths + 1:
self.rate = self.nextRate
self.payment = findPayment(self.owed[-1], self.rate, self.months - self.teaserMonths)
#********** End *********#
Mortgage.makePayment(self)
if __name__=="__main__":
print(Fixed(100000, 6.5, 36))
print(Fixed(100000, 6.5, 120))
print(FixedWithPoints(100000, 6.5, 36, 20))
print(FixedWithPoints(100000, 6.5, 120, 20))
print(TwoRate(100000, 9.0, 36, 4.8, 12))
print(TwoRate(100000, 7.0, 120, 4.8, 36))
第3關:比較各種貸款的利弊
def findPayment(loan, r, m):
return loan * ((r * (1 + r) ** m) / ((1 + r) ** m - 1))
class Mortgage(object):
def __init__(self, loan, annRate, months):
self.loan = loan
self.rate = annRate / 1200.0
self.months = months
self.paid = [0.0]
self.owed = [loan]
self.payment = findPayment(loan, self.rate, self.months)
self.legend = None
def makePayment(self):
self.paid.append(self.payment)
reduction = self.payment - self.owed[-1] * self.rate
self.owed.append(self.owed[-1] - reduction)
def getTotalPaid(self):
return sum(self.paid)
def __str__(self):
return str(self.legend)
class Fixed(Mortgage):
def __init__(self, loan, r, months):
Mortgage.__init__(self, loan, r, months)
self.legend = 'Fixed, ' + str(r) + '%, for ' + str(months) + ' months'
class FixedWithPoints(Mortgage):
def __init__(self, loan, r, months, pts):
Mortgage.__init__(self, loan, r, months)
self.pts = pts
self.paid = [loan * (pts / 100.0)]
self.legend = 'Fixed, ' + str(r) + '%, ' + str(pts) + ' points, for ' + str(months) + ' months'
class TwoRate(Mortgage):
def __init__(self, loan, r, months, teaserRate, teaserMonths):
Mortgage.__init__(self, loan, teaserRate, months)
self.teaserMonths = teaserMonths
self.teaserRate = teaserRate/1200
self.nextRate = r / 1200.0
self.legend = str(teaserRate)\
+ '% for ' + str(self.teaserMonths)\
+ ' months, \n then ' + str(r) + '%, for ' + str(months) + ' months'
def makePayment(self):
if len(self.paid) == self.teaserMonths + 1:
self.rate = self.nextRate
self.payment = findPayment(self.owed[-1], self.rate, self.months - self.teaserMonths)
Mortgage.makePayment(self)
def compareMortgages(amt, years, fixedRate, pts, ptsRate, varRate1, varRate2, varMonths):
# 請在此添加代碼,補全函數compareMortgages
#********** Begin *********#
morts = []
morts.append(Fixed(amt, fixedRate, years*12))
morts.append(FixedWithPoints(amt, ptsRate, years*12, pts))
morts.append(TwoRate(amt, varRate2, years*12, varRate1, varMonths))
for i in range(3):
totMonths = morts[i].months
for m in range(totMonths):
morts[i].makePayment()
for m in morts:
print(m)
print('Loan ' + str(amt) + ' Total payments = ' + str(int(m.getTotalPaid())))
if __name__=="__main__":
compareMortgages(200000, 30, 7, 3.25, 5, 4.5, 9.5, 48)
print('*'*40)
compareMortgages(1000000, 30, 7, 20, 5, 4.5, 9.5, 48)
print('*' * 40)
compareMortgages(500000, 10, 7, 20, 5, 4.5, 9.5, 48)
面向對象(二)-----綜合編程2
第1關:定義三維向量類
class Vector3d:
# 請在這裏補充代碼,完成本關任務
#********** Begin *********#
def __init__(self, x, y, z):
self.__x = x
self.__y = y
self.__z = z
#********** End *********#
第2關:定義實例方法計算三維向量的長度
class Vector3d:
def __init__(self, x, y, z):
self.__x = x
self.__y = y
self.__z = z
def length(self):
# 請在這裏補充代碼,完成本關任務
#********** Begin *********#
return (self.__x**2 + self.__y**2 + self.__z**2)**0.5
#********** End *********#
第3關:實現三維向量之間的加法與減法
class Vector3d:
def __init__(self, x, y, z):
self.__x = x
self.__y = y
self.__z = z
def length(self):
return (self.__x**2 + self.__y**2 + self.__z**2) ** 0.5
# 請在這裏增加3個特殊方法,分別用來支持加法運算符、減法運算符以實現兩個三維向量間的加法和減法運算,以及打印函數print()
#********** Begin *********#
def __str__(self):
return '(' + str(self.__x) + ', ' + str(self.__y) + ', ' + str(self.__z) + ')'
def __add__(self, v):
return Vector3d(self.__x + v.__x, self.__y + v.__y, self.__z + v.__z )
def __sub__(self, v):
return Vector3d(self.__x - v.__x, self.__y - v.__y, self.__z - v.__z )
#********** End *********#