声明一个类Person,成员变量有姓名、出生年月、性别。有成员方法以显示姓名、年龄和性别
时间: 2024-02-01 18:01:58 浏览: 122
。class Person:
def __init__(self, name, birth_year, sex):
self.name = name
self.birth_year = birth_year
self.sex = sex
def display_info(self):
age = 2021 - self.birth_year
print(f"Name: {self.name}, Age: {age}, Sex: {self.sex}")
相关问题
用JAVA声明一个类person,成员变量变量有姓名、出生年月、性别、有成员方法以显示姓名年龄和性别
好的,以下是用JAVA声明一个类person的代码:
```
public class Person {
private String name;
private int birthYear;
private int birthMonth;
private int birthDay;
private String gender;
public Person(String name, int birthYear, int birthMonth, int birthDay, String gender) {
this.name = name;
this.birthYear = birthYear;
this.birthMonth = birthMonth;
this.birthDay = birthDay;
this.gender = gender;
}
public String getName() {
return name;
}
public int getBirthYear() {
return birthYear;
}
public int getBirthMonth() {
return birthMonth;
}
public int getBirthDay() {
return birthDay;
}
public String getGender() {
return gender;
}
public void displayInfo() {
int age = calculateAge();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Gender: " + gender);
}
private int calculateAge() {
LocalDate birthdate = LocalDate.of(birthYear, birthMonth, birthDay);
LocalDate now = LocalDate.now();
return Period.between(birthdate, now).getYears();
}
}
```
这个类有五个成员变量:姓名、出生年月、性别。它还有一个构造函数,用于初始化这些成员变量。它还有一个名为displayInfo的成员方法,用于显示姓名、年龄和性别。这个类还有一个私有方法calculateAge,用于计算年龄。
编程题:声明一个类Person,成员变量有姓名、出生年月、性别、有成员方法以显示姓名、年龄和性别。
好的,这是一个简单的类定义:
```python
class Person:
def __init__(self, name, birthdate, gender):
self.name = name
self.birthdate = birthdate
self.gender = gender
def display_info(self):
print(f"姓名:{self.name},年龄:{self.get_age()},性别:{self.gender}")
def get_age(self):
today = date.today()
age = today.year - self.birthdate.year
if today.month < self.birthdate.month or (today.month == self.birthdate.month and today.day < self.birthdate.day):
age -= 1
return age
```
这个类有一个构造函数,用于初始化成员变量,还有一个 `display_info` 方法,用于显示姓名、年龄和性别。`get_age` 方法用于计算年龄。
阅读全文