python创建一个反映学生基本属性(name.sdept)和方法(eat.learn)的类,并实例化。【注:吃肉餐费10元,其他餐5元,学生会学习多门课程,只有学习到python课程,才会“前程似锦”,其他都是“道路曲折”】
时间: 2023-11-27 14:02:48 浏览: 29
可以用以下代码来创建该类和实例化:
```python
class Student:
def __init__(self, name, sdept):
self.name = name
self.sdept = sdept
def eat(self, meal):
if meal == 'meat':
cost = 10
else:
cost = 5
print(f"{self.name} ate {meal} and paid {cost} yuan.")
def learn(self, course):
if course == 'python':
result = "前程似锦"
else:
result = "道路曲折"
print(f"{self.name} learned {course} and got the result of {result}.")
```
使用这个类来实例化一个学生对象:
```python
stu = Student('Tom', 'Computer Science')
```
现在我们可以调用该对象的方法,比如:
```python
stu.eat('meat')
stu.learn('python')
```
这将输出:
```
Tom ate meat and paid 10 yuan.
Tom learned python and got the result of 前程似锦.
```