达内作业题:用python写出两个人类及其互动行为
class Human: """ 一个简单的人类类 """ def __init__(self, name, age): """ 初始化方法 :param name: str, 人类的名字 :param age: int, 人类的年龄 """ self.name = name # 人类的名字 self.age = age # 人类的年龄 self.can = [] # 人类会的技能 self.money = 0 # 人类拥有的金钱 def show_info(self): """ 展示人类的信息 """ print(self.age, '的', self.name, '有', self.money, '元钱,他学会的技能有:', self.can) def teach(self, other, can_name): """ 教授技能 :param other: Human, 被教授的对象 :param can_name: str, 技能名称 """ other.can.append(can_name) print(self.name, '教', other.name, '学', can_name) def work(self, money): """ 工作 :param money: int, 赚取的金钱 """ self.money += money print(self.name, '工作赚了', money, '元钱') def borrow(self, other, money): """ 借钱 :param other: Human, 被借钱的对象 :param money: int, 借到的金钱 """ if other.money < money: print(self.name, '没有足够的钱') return other.money -= money self.money += money print(self.name, '向', other.name, '借了', money, '元钱') zs = Human('张三', 28) # 创建张三 ls = Human('李四', 8) # 创建李四 zs.teach(ls, 'python') # 张三教李四学python ls.teach(zs, '王者荣耀') # 李四教张三王者荣耀 zs.work(1000) # 张三工作赚了1000元钱 ls.borrow(zs, 200) # 李四向张三借了200元钱 zs.show_info() # 展示张三的信息 ls.show_info() # 展示李四的信息
这段代码展示了一个名为 Human 的 Python 类,其中包含了人类的基本属性和行为,如教学、工作和借贷。通过创建实例并调用方法,展示了两个人类之间的互动情况。
发表评论