python面向对象练习题
时间: 2023-10-14 19:30:24 浏览: 128
好的,以下是一些Python面向对象练习题:
1. 创建一个名为Person的类,包含属性name和age。创建一个对象并打印其属性。
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("John", 25)
print(person1.name)
print(person1.age)
```
2. 创建一个名为Rectangle的类,包含属性width和height。定义一个方法用于计算矩形的面积。创建一个矩形对象并打印其面积。
```python
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
rectangle1 = Rectangle(5, 10)
print(rectangle1.area())
```
3. 创建一个名为BankAccount的类,包含属性balance和owner。定义方法用于存款、取款和打印余额。创建一个银行账户对象并进行操作。
```python
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
print("Deposit successful.")
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
print("Withdrawal successful.")
else:
print("Insufficient funds.")
def check_balance(self):
print("Balance: ", self.balance)
account1 = BankAccount("John Doe", 1000)
account1.deposit(500)
account1.check_balance()
account1.withdraw(2000)
account1.check_balance()
```
4. 创建一个名为Vehicle的类,包含属性manufacturer和model。创建两个子类,Car和Motorcycle,并添加属性num_doors和num_wheels。创建一个车辆对象并打印其属性。
```python
class Vehicle:
def __init__(self, manufacturer, model):
self.manufacturer = manufacturer
self.model = model
class Car(Vehicle):
def __init__(self, manufacturer, model, num_doors):
super().__init__(manufacturer, model)
self.num_doors = num_doors
class Motorcycle(Vehicle):
def __init__(self, manufacturer, model, num_wheels):
super().__init__(manufacturer, model)
self.num_wheels = num_wheels
vehicle1 = Car("Toyota", "Corolla", 4)
print(vehicle1.manufacturer)
print(vehicle1.model)
print(vehicle1.num_doors)
vehicle2 = Motorcycle("Harley-Davidson", "Sportster", 2)
print(vehicle2.manufacturer)
print(vehicle2.model)
print(vehicle2.num_wheels)
```
这些练习题可以帮助你巩固Python面向对象编程的基础知识。祝你练习愉快!
阅读全文