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 [6]:
# Bài tập về động vật
# Xây dưng class "cha" (base class):
class Animal:
#constructor: xây dựng ra đối tượng
def __init__(self, animalTypeA, nameA, widthA, heightA, weightA):
self.animalType = animalTypeA
self.name = nameA
self.width = widthA
self.height = heightA
self.weight = weightA
# phát ra âm thanh:
def makeVoice(self):
print("Unknow voice")
# in thông tin
def printMe(self):
print("animalType: {0}, name={1}, width={2}, height={3}, weight={4}".format(self.animalType,self.name, self.width, self.height, self.weight))
In [7]:
a1 = Animal("Con người", "Nguyễn Văn A", "" , "170cm", "60kg")
a1.printMe()
a1.makeVoice()
animalType: Con người, name=Nguyễn Văn A, width=, height=170cm, weight=60kg Unknow voice
In [17]:
class Dog(Animal):
#constructor của lớp con:
def __init__(self, nameA, widthA, heightA, weightA, isChampionA):
# gọi constructor của lớp cha
Animal.__init__(self, "Dog", nameA, widthA, heightA, weightA)
# gán giá trị cho các thuộc tính bổ sung
self.isChampion = isChampionA
# override method
def makeVoice(self):
print("{0}: gau gau".format(self.name))
def takeCareHome(self):
print("{0}: zzzZZZZZ".format(self.name))
In [19]:
dog1 = Dog("Cậu Vàng", "80cm", "40cm", "20kg", True)
dog2 = Dog("Mật", "850cm", "100m", "50kg", True)
dog1.makeVoice()
dog1.printMe()
dog1.takeCareHome()
dog2.makeVoice()
dog2.printMe()
Cậu Vàng: gau gau animalType: Dog, name=Cậu Vàng, width=80cm, height=40cm, weight=20kg Cậu Vàng: zzzZZZZZ Mật: gau gau animalType: Dog, name=Mật, width=850cm, height=100m, weight=50kg
In [20]:
class Cat(Animal):
#constructor
def __init__(self, nameA, widthA, heightA, weightA, colorA):
# gọi constructor của lớp cha
Animal.__init__(self, "Cat", nameA, widthA, heightA, weightA)
# gán giá trị cho các thuộc tính bổ sung
self.colorA = colorA
# Override method
def makeVoice(self):
print("{0}: meow meow".format(self.name))
def catchMouse(self):
print("{0}: catch a mouse".format(self.name))
In [21]:
cat1 = Cat("Mimi", "30cm", "10cm", "2kg", "Black")
cat2 = Cat("Tom", "80cm", "30cm", "20kg", "Blue")
cat1.printMe()
cat1.makeVoice()
cat2.printMe()
cat2.makeVoice()
cat2.catchMouse()
animalType: Cat, name=Mimi, width=30cm, height=10cm, weight=2kg Mimi: meow meow animalType: Cat, name=Tom, width=80cm, height=30cm, weight=20kg Tom: meow meow Tom: catch a mouse
Không có nhận xét nào:
Đăng nhận xét