Professional Documents
Culture Documents
CS121 BT Tuan3 OOP Lop DapAn
CS121 BT Tuan3 OOP Lop DapAn
CS121 BT Tuan3 OOP Lop DapAn
● Xây dựng phương thức khởi tạo truyền vào 2 tham số khởi tạo cho hoành độ và
tung độ
● Xây dựng phương thức __str__ để có thể in các đối tượng Coordinate dưới dạng
“(1.5, 2.3)”
● Xây dựng phương thức tính khoảng cách giữa 2 đối tượng Coordinate
Viết đoạn mã sử dụng lớp Coordinate và các phương thức vừa xây dựng
class Coordinate(object):
""" A coordinate made up of an x and y value """
def __init__(self, x, y):
""" Sets the x and y values """
self.x = x
self.y = y
def __str__(self):
""" Returns a string representation of self """
return "<" + str(self.x) + "," + str(self.y) + ">"
def distance(self, other):
""" Returns the euclidean distance between two points
"""
x_diff_sq = (self.x-other.x)**2
y_diff_sq = (self.y-other.y)**2
return (x_diff_sq + y_diff_sq)**0.5
c = Coordinate(3,4)
origin = Coordinate(0,0)
print(c.x, origin.x)
print(c.distance(origin))
print(Coordinate.distance(c, origin))
print(origin.distance(c))
print(c)
Bài 2.
Viết class Fraction (phân số) mô tả khái niệm phân số. Mỗi phân số có 2 thuộc tính dạng
số nguyên là tử số và mẫu số (mẫu số phải khác không)
● Xây dựng phương thức khởi tạo truyền vào 2 tham số khởi tạo cho tử số và mẫu
số
● Xây dựng phương thức __str__ để có thể in các đối tượng Fraction dưới dạng
“2/3”
● Xây dựng phương thức tính cộng, trừ 2 phân số
● Xây dựng phương thức trả lại giá trị của phân số dưới dạng float
class Fraction(object):
"""
A number represented as a fraction
"""
def __init__(self, num, denom):
""" num and denom are integers """
assert type(num) == int and type(denom) == int, "ints
not used"
self.num = num
self.denom = denom
def __str__(self):
""" Retunrs a string representation of self """
return str(self.num) + "/" + str(self.denom)
def __add__(self, other):
""" Returns a new fraction representing the addition """
top = self.num*other.denom + self.denom*other.num
bott = self.denom*other.denom
return Fraction(top, bott)
def __sub__(self, other):
""" Returns a new fraction representing the subtraction
"""
top = self.num*other.denom - self.denom*other.num
bott = self.denom*other.denom
return Fraction(top, bott)
def __float__(self):
""" Returns a float value of the fraction """
return self.num/self.denom
def inverse(self):
""" Returns a new fraction representing 1/self """
return Fraction(self.denom, self.num)
a = Fraction(1,4)
b = Fraction(3,4)
c = a + b # c is a Fraction object
print(c)
print(float(c))
print(Fraction.__float__(c))
print(float(b.inverse()))
##c = Fraction(3.14, 2.7) # assertion error
##print a*b # error, did not define how to multiply two Fraction
objects
Bài 3.
Viết class IntSet (tập hợp các số nguyên) mô tả một tập hợp các số nguyên. Class này cho
phép khởi tạo, thêm, bớt số nguyên vào tập hợp, cho phép kiểm tra một số nguyên có nằm
trong tập hợp hay không, cho phép in ra danh sách các số trong tập hợp.
Viết đoạn mã sử dụng lớp IntSet và các phương thức vừa xây dựng
class intSet(object):
"""An intSet is a set of integers
The value is represented by a list of ints, self.vals.
Each int in the set occurs in self.vals exactly once."""
def __init__(self):
"""Create an empty set of integers"""
self.vals = []
def insert(self, e):
"""Assumes e is an integer and inserts e into self"""
if not e in self.vals:
self.vals.append(e)
def __str__(self):
"""Returns a string representation of self"""
self.vals.sort()
result = ''
for e in self.vals:
result = result + str(e) + ','
return '{' + result[:-1] + '}'
#s = intSet()
#print(s)
#s.insert(3)
#s.insert(4)
#s.insert(3)
#print(s)
#s.member(3)
#s.member(5)
#s.insert(6)
#print(s)
#s.remove(3)
#print(s)
##s.remove(3)
Bài 4.
Viết class Date (ngày tháng năm) mô tả một ngày trong năm . Lớp này lưu thông tin của
một ngày bằng 3 số nguyên: month (tháng), day (ngày) và year (năm).
● Xây dựng phương thức khởi tạo truyền vào 3 tham số cho class Date
● Xây dựng phương thức chuyển từ Date sang string theo định dạng ngày/tháng/năm
● Xây dựng phương thức kiểm tra ngày tháng của đối tượng có hợp lệ hay không. Ví
dụ “31/2/2009” là ngày không hợp lệ vì tháng 2 không có ngày 31.
def checkLeapYear(year):
if isinstance(year, int) == False:
return False
if year % 400 == 0:
return True
if year % 100 == 0:
return False
if year % 4 == 0:
return True
return False
class Date(object):
def __init__(self, day, month, year):
self.day = day
self.month = month
self.year = year
def __str__(self):
result = str(self.day) + "/" \
+ str(self.month) + "/" \
+ str(self.year)
return result
def validate(self):
if not (isinstance(self.day, int) and \
isinstance(self.month, int) and \
isinstance(self.year, int)):
return False
if self.day < 1 or self.day > 31:
return False
if self.month < 1 or self.month > 12:
return False
date1 = Date(29,2,1904)
print(date1)
print(date1.validate())
Bài 5.
Viết class Person (con người) mô tả thông tin cơ bản của một người gồm họ tên, số
chứng minh thư, ngày sinh. trong đó ngày sinh có kiểu là Date (sử dụng lại bài 4)
● Xây dựng phương thức khởi tạo không tham số cho class Person
● Xây dựng phương thức nhập thông tin người dùng cho class Person
● Xây dựng phương thức __str__ để có thể in ra thông tin của một Person
def checkLeapYear(year):
if isinstance(year, int) == False:
return False
if year % 400 == 0:
return True
if year % 100 == 0:
return False
if year % 4 == 0:
return True
return False
class Date(object):
def __init__(self, day, month, year):
self.day = day
self.month = month
self.year = year
def __str__(self):
result = str(self.day) + "/" \
+ str(self.month) + "/" \
+ str(self.year)
return result
def validate(self):
if not (isinstance(self.day, int) and \
isinstance(self.month, int) and \
isinstance(self.year, int)):
return False
if self.day < 1 or self.day > 31:
return False
if self.month < 1 or self.month > 12:
return False
def __str__(self):
s = "Ho ten: " + self.name + "\n"
s += "CCCD: " + self.id + "\n"
s += "Ngay sinh:" + str(self.birthDay) + "\n"
return s
person1 = Person()
person1.inputInfo()
print(person1)
Bài 6.
Viết class Item mô tả một mặt hàng trong siêu thị. Mỗi item phải có các thông tin sau:
- ID: là một số nguyên để nhận dạng mặt hàng, mỗi mặt hàng có 1 id riêng không
trùng nhau
- name: tên mặt hàng
- cost: giá tiền
Thực hiện các yêu cầu sau:
● Xây dựng phương thức khởi tạo, phương thức in ra thông tin, phương thức chuyển
sang dạng string cho class Item
● Xây dựng phương thức nhập thông cho class Item
● Xây dựng phương thức sửa thông cho class Item
def __str__(self):
s = "ID: " + str(self.id) + "\n"
s += "Name: " + self.name + "\n"
s += "Cost:" + str(self.cost) + "\n"
return s
def inputInfo(self):
self.id = int(input("Moi nhap ID: "))
self.name = input("Moi nhap ten mat hang: ")
self.cost = int(input("Moi nhap gia ca: "))
def editInfo(self):
print("Thong tin hien tai: ")
print(self)
while(True):
print("1. sua id")
print("2. sua ten mat hang")
print("3. sua gia ban")
print("4. thoat")
select = int(input("Moi chon chuc nang: "))
if select == 1:
self.id = int(input("Moi nhap id moi: "))
elif select == 2:
self.name = input("Moi nhap ten moi: ")
elif select == 3:
self.cost = int(input("Moi nhap gia moi: "))
else:
break
print("Sua thanh cong.\n")