CS121 BT Tuan3 OOP Lop DapAn

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Bài tập Tuần 3

Lập trình hướng đối tượng (Lớp và phương thức).

Giảng viên Giới thiệu sơ lược về class, method


Thị phạm về tạo class, method
Giao bài tập cho sinh viên
Kiểm tra bài tập của sinh viên
Sinh viên Thực hành các bài tập

Danh sách bài tập


Bài 1.
Viết class Coordinate (tọa độ) mô tả tọa độ 2D của một điểm. class này yêu cầu 2 thuộc
tính dạng số là hoành độ X và tung độ Y.

● 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

Đáp án tham khảo (code hoặc tên file code)

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

● Xây dựng phương thức trả lại phân số nghịch đảo


Viết đoạn mã sử dụng lớp Fraction và các phương thức vừa xây dựng

Đáp án tham khảo (code hoặc tên file code)

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

Đáp án tham khảo (code hoặc tên file code)

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 member(self, e):


"""Assumes e is an integer
Returns True if e is in self, and False otherwise"""
return e in self.vals

def remove(self, e):


"""Assumes e is an integer and removes e from self
Raises ValueError if e is not in self"""
try:
self.vals.remove(e)
except:
raise ValueError(str(e) + ' not found')

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.

Đáp án tham khảo (code hoặc tên file code)

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

dayOfMonth = [31, 28, 31, 30, 31, 30, 31, \


31, 30, 31, 30, 31]
if checkLeapYear(self.year):
dayOfMonth[1] = 29
if self.day > dayOfMonth[self.month-1]:
return False
return True

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

Đáp án tham khảo (code hoặc tên file code)

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

dayOfMonth = [31, 28, 31, 30, 31, 30, 31, \


31, 30, 31, 30, 31]
if checkLeapYear(self.year):
dayOfMonth[1] = 29
if self.day > dayOfMonth[self.month-1]:
return False
return True

class Person (object):


def __init__(self):
pass
def inputInfo(self):
self.name = input("Moi nhap ho ten: ")
self.id = input("Moi nhap so CCCD: ")
print("Moi nhap ngay sinh gom ngay thang nhau cach nhau
boi dau cach")
birthDayStr = input("Ngay sinh : ").split()
self.birthDay = Date(int(birthDayStr[0]), \
int(birthDayStr[1]), \
int(birthDayStr[2]))

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

Đáp án tham khảo (code hoặc tên file code)

class Item (object):


def __init__(self, id, name, cost):
self.id = id
self.name = name
self.cost = cost

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")

item = Item(1, "keo", 500)


item.editInfo()
print(item)

You might also like