Bản quyền thuộc về TITV.vn,
vui lòng không đăng tải lại nội dung từ trang này.
Video giải thích chi tiết
Nội dung chi tiết
In [1]:
# Ví dụ về tạo class đơn giản
class SimpleClass:
# Attribute
i=5
# _init_
def __init__(self):
self.j = 7
# methods:
def printMe(self):
print(self.j)
In [2]:
objectA = SimpleClass()
objectB = SimpleClass()
objectA.printMe()
print(objectB.i)
7 5
In [3]:
# Thay đổi giá trị của thuộc tính
objectA.i = 100
objectB.j = 500
print(objectA.i)
objectB.printMe()
100 500
In [4]:
# Thư truy cập phương thức ko phải static
SimpleClass.printMe()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-4-3e765c98ae4f> in <module> 1 # Thư truy cập phương thức ko phải static ----> 2 SimpleClass.printMe() TypeError: printMe() missing 1 required positional argument: 'self'
In [5]:
class SimpleClass2:
# constructor
def __init__(self):
self.name="Tung"
# methods
def hello(self):
print("Hello "+ self.name)
# static methods
@staticmethod
def hi(name):
print("Hi " + name);
In [8]:
objectC = SimpleClass2()
objectD = SimpleClass2()
objectC.hello()
objectC.hi("Peter")
#SimpleClass2.hello()
SimpleClass2.hi("Peter")
Hello Tung Hi Peter Hi Peter
In [ ]:
class Ngay:
# Constructor
def __init__(self, giatri_ngay, giatri_thang, giatri_nam):
self.ngay = giatri_ngay
self.thang = giatri_thang
self.nam = giatri_nam
# xác định số ngày của tháng:
@staticmethod
def soNgayCuaThang(thang, nam):
if (thang in [1,3,5,7,8,10,12]):
return 31
elif (thang in [4,6,9,11]):
return 30
elif (thang==2):
if (nam%400==0 or (nam%4==0 and nam%100 != 0)):
return 29
else:
return 28
# 15/3/2022:
# Tháng 1: 31 ngày
# Tháng 2: 28 ngày
# 31 + 28 + 15 = ?
def ngayTrongNam(self):
giaTriNgayTrongNam = 0
# Tính tổng số lượng ngày của những tháng trước
for x in range(1, self.thang):
giaTriNgayTrongNam += self.soNgayCuaThang(x, self.nam)
# Cộng thêm số ngày của tháng hiện tại
giaTriNgayTrongNam+=self.ngay
# Trả kết quả
return giaTriNgayTrongNam
In [ ]:
ngayA = Ngay(15, 3, 2022)
print(ngayA.ngayTrongNam())
ngayB = Ngay(15, 1, 2022)
print(ngayB.ngayTrongNam())
74 15
Không có nhận xét nào:
Đăng nhận xét