定义一个学生类,创建它的两个对象
时间: 2023-05-19 10:01:50 浏览: 56
好的,以下是一个简单的学生类的定义和创建两个对象的示例代码:
```python
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
student1 = Student("张三", 18, "高三")
student2 = Student("李四", 17, "高二")
```
这个学生类有三个属性:姓名、年龄和年级,使用 `__init__` 方法初始化。创建两个对象时,分别传入不同的参数,即可得到两个不同的学生对象。
相关问题
用java写一个定义一个学生类,创建它的两个对象
非常好的问题!以下是一个简单的Java代码,定义了一个名为Student的类,并创建了两个Student对象:
```
public class Student {
String name;
int age;
String major;
public Student(String name, int age, String major) {
this.name = name;
this.age = age;
this.major = major;
}
public static void main(String[] args) {
Student student1 = new Student("张三", 20, "计算机科学");
Student student2 = new Student("李四", 21, "软件工程");
System.out.println("学生1的姓名:" + student1.name);
System.out.println("学生1的年龄:" + student1.age);
System.out.println("学生1的专业:" + student1.major);
System.out.println("学生2的姓名:" + student2.name);
System.out.println("学生2的年龄:" + student2.age);
System.out.println("学生2的专业:" + student2.major);
}
}
```
希望这个例子能够帮助你理解如何定义一个类并创建对象。
定义一个学生类,创建两个学生对象,实现二人对话
好的,下面是一个简单的学生类定义和两个学生对象的对话实现:
```python
class Student:
def __init__(self, name):
self.name = name
def talk(self, other):
print(f"{self.name}: 你好,{other.name}!")
print(f"{other.name}: 你好,{self.name}!")
# 创建两个学生对象
s1 = Student("小明")
s2 = Student("小红")
# 二人对话
s1.talk(s2)
```
输出结果如下:
```
小明: 你好,小红!
小红: 你好,小明!
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)