《案例003:类、对象、继承和多态》

学习面向对象编程:了解类、对象、继承和多态等面向对象编程的基本概念,并学习如何在Python中应用它们。

1、创建一个名为Person的类,包含属性name和age,并实例化对象。

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("John", 25)

2、创建一个名为Dog的类,包含方法bark(),并实例化对象。

class Dog:
    def bark(self):
        print("Woof!")

dog = Dog()
dog.bark()

3、创建一个名为Rectangle的类,包含属性length和width,并实现计算面积和周长的方法。

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def calculate_area(self):
        return self.length * self.width

    def calculate_perimeter(self):
        return 2 * (self.length + self.width)

rectangle = Rectangle(5, 3)
area = rectangle.calculate_area()
perimeter = rectangle.calculate_perimeter()

4、创建一个名为BankAccount的类,包含属性balance和方法deposit()和withdraw()。

class BankAccount:
    def __init__(self):
        self.balance = 0

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

    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
        else:
            print("Insufficient funds")

account = BankAccount()
account.deposit(100)
account.withdraw(50)

5、创建一个名为Circle的类,包含属性radius和方法计算面积和周长。

import math

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def calculate_area(self):
        return math.pi * self.radius**2

    def calculate_circumference(self):
        return 2 * math.pi * self.radius

circle = Circle(2)
area = circle.calculate_area()
circumference = circle.calculate_circumference()

6、创建一个名为Student的类,包含属性name和grade,并实现打印学生信息的方法。

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def print_info(self):
        print("Name:", self.name)
        print("Grade:", self.grade)

student = Student("Alice", 10)
student.print_info()

7、创建一个名为Employee的类,包含属性name和salary,并实现打印员工信息的方法。

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def print_info(self):
        print("Name:", self.name)
        print("Salary:", self.salary)

employee = Employee("John", 5000)
employee.print_info()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大大大钢琴

喜欢!就请他吃3块钱好吃的吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值