本博文源於python基礎,旨在完成對對象的構造。
原題如下:
假設某遊戲項目中需要定義一個精靈對象,其所需的屬性有體重、顏色、高度、能量;具有
行走、跳躍、進食能力且會在行走和跳躍時會不斷消耗能量,而進食則會增加能量,請根據描述定義這個
精靈類
實驗效果
實驗原理
將屬性都定義爲私有屬性,將增加和消耗能量全部封裝成私有方法,根據不同實例方法進行調用就行了,
實驗代碼
class jl(object):
def __init__(self, weight=10, color='red', height=168, energy=100):
self.__weight = weight
self.__color = color
self.__height = height
self.__energy = energy
self.getInfo()
def __addEnergy(self):
self.__energy += 5
def __reduceEnergy(self):
self.__energy -= 5
# 行走損失能量5
def walk(self):
print('行走中....')
self.__reduceEnergy()
self.getInfo()
# 進食物增加能量
def eat(self):
print('進食中....')
self.__addEnergy()
self.getInfo()
# 跳躍損失能量
def jump(self):
print('跳躍中...')
self.__energy -= 5
self.getInfo()
def getInfo(self):
print("當前能量值爲:%d" % self.__energy)
jlw = jl(20, 'blue', 170, 120)
jlw.eat()
jlw.jump()
jlw.jump()
jlw.jump()
jlw.jump()
jlw.jump()
jlw.walk()