Python类的编程题入门题目

你好,我是悦创。

1. 定义一个"狗"的类

题目描述

定义一个名为Dog的类,其中:

  • Dog类应有一个name(名字)属性和一个age(年龄)属性。
  • Dog类应有一个方法叫做bark,当调用这个方法时,它应返回"Woof!"
  • Dog类应有一个方法叫做get_human_age,它应返回狗的年龄乘以7(因为一般认为1年的狗相当于7岁的人)。

示例代码

python 复制代码
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        return "Woof!"

    def get_human_age(self):
        return self.age * 7

dog = Dog("Buddy", 3)
print(dog.bark())           # 输出: Woof!
print(dog.get_human_age())  # 输出: 21

2. 创建一个"银行账户"的类

题目描述

定义一个名为BankAccount的类,其中:

  • BankAccount类应有一个balance(余额)属性,初始化时默认为0。
  • BankAccount类应有一个方法叫做deposit,可以存款。
  • BankAccount类还应有一个方法叫做withdraw,可以取款。如果取款金额大于余额,则应返回"Insufficient funds!"

示例代码

python 复制代码
class BankAccount:
    def __init__(self, balance=0):
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if amount > self.balance:
            return "Insufficient funds!"
        else:
            self.balance -= amount

account = BankAccount()
account.deposit(100)
print(account.balance)       # 输出: 100
print(account.withdraw(120)) # 输出: Insufficient funds!

3. 创建一个"学生"的类

题目描述

定义一个名为Student的类,其中:

  • Student类应有name(名字)属性和grades(成绩)属性,成绩是一个列表。
  • Student类应有一个方法叫做average_grade,返回该学生的平均成绩。

示例代码

python 复制代码
class Student:
    def __init__(self, name, grades=[]):
        self.name = name
        self.grades = grades

    def average_grade(self):
        return sum(self.grades) / len(self.grades)

student = Student("Alice", [90, 85, 88, 95])
print(student.average_grade())  # 输出: 89.5
相关推荐
可爱de艺艺几秒前
Go入门之struct
开发语言·后端·golang
信徒_4 分钟前
Go 语言中的协程
开发语言·后端·golang
阿正的梦工坊4 分钟前
Sliding Window Attention(滑动窗口注意力)解析: Pytorch实现并结合全局注意力(Global Attention )
人工智能·pytorch·python
begei8 分钟前
飞牛os使用ddns-go配合华为云实现内网穿透
开发语言·golang·华为云
喜-喜28 分钟前
Python pip 缓存清理:全面方法与操作指南
python·缓存·pip
rgb2gray29 分钟前
GeoHD - 一种用于智慧城市热点探测的Python工具箱
人工智能·python·智慧城市
向哆哆39 分钟前
Java应用程序的跨平台性能优化研究
java·开发语言·性能优化
MZWeiei1 小时前
Matplotlib,Streamlit,Django大致介绍
python·django·matplotlib
free-elcmacom1 小时前
C语言番外篇(3)------------>break、continue
c语言·开发语言
卑微的小鬼1 小时前
Go 语言结合 Redis 实现固定窗口、滑动窗口、令牌桶和漏桶限流算法的示例代码
开发语言·redis·golang