python自定义类题库
时间: 2023-11-05 22:03:26 浏览: 85
1. 编写一个名为Person的类,包含姓名、年龄、性别三个属性,并提供相应的构造函数和方法。
```python
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def get_name(self):
return self.name
def get_age(self):
return self.age
def get_gender(self):
return self.gender
def set_name(self, name):
self.name = name
def set_age(self, age):
self.age = age
def set_gender(self, gender):
self.gender = gender
```
2. 编写一个名为Rectangle的类,包含长、宽两个属性,并提供计算周长和面积的方法。
```python
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def get_length(self):
return self.length
def get_width(self):
return self.width
def get_area(self):
return self.length * self.width
def get_perimeter(self):
return (self.length + self.width) * 2
```
3. 编写一个名为Student的类,包含学号、姓名、性别、年龄、成绩五个属性,并提供相应的构造函数和方法。
```python
class Student:
def __init__(self, id, name, gender, age, score):
self.id = id
self.name = name
self.gender = gender
self.age = age
self.score = score
def get_id(self):
return self.id
def get_name(self):
return self.name
def get_gender(self):
return self.gender
def get_age(self):
return self.age
def get_score(self):
return self.score
def set_id(self, id):
self.id = id
def set_name(self, name):
self.name = name
def set_gender(self, gender):
self.gender = gender
def set_age(self, age):
self.age = age
def set_score(self, score):
self.score = score
```
4. 编写一个名为BankAccount的类,包含账户名、账号、余额三个属性,并提供存款、取款和查询余额的方法。
```python
class BankAccount:
def __init__(self, name, account, balance):
self.name = name
self.account = account
self.balance = balance
def get_name(self):
return self.name
def get_account(self):
return self.account
def get_balance(self):
return self.balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
else:
print("余额不足!")
def inquiry(self):
print("账户名:", self.name)
print("账号:", self.account)
print("余额:", self.balance)
```
5. 编写一个名为Car的类,包含品牌、型号、颜色三个属性,并提供启动、加速、刹车和查询速度的方法。
```python
class Car:
def __init__(self, brand, model, color):
self.brand = brand
self.model = model
self.color = color
self.speed = 0
def get_brand(self):
return self.brand
def get_model(self):
return self.model
def get_color(self):
return self.color
def start(self):
print("汽车启动!")
def accelerate(self, speed):
self.speed += speed
print("汽车当前速度为:", self.speed)
def brake(self):
self.speed = 0
print("汽车已刹车!")
def get_speed(self):
return self.speed
```
阅读全文