创建一个名为 `Person` 的类,包含以下属性:`name`、`age`、`gender` 和 `nationality`。`nationality` 是一个类变量。创建一个方法 `change_nationality()`,用于更改人的国籍。请给出使用示例
时间: 2023-10-23 19:08:49 浏览: 207
java代码-使用java构造Person类。包括姓名(name),性别和年龄(age)的源代码
5星 · 资源好评率100%
```python
class Person:
nationality = 'unknown'
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def change_nationality(self, nationality):
Person.nationality = nationality
# 使用示例
person1 = Person('Tom', 30, 'male')
person2 = Person('Lily', 25, 'female')
print(person1.nationality) # 输出:unknown
print(person2.nationality) # 输出:unknown
person1.change_nationality('USA')
print(person1.nationality) # 输出:USA
print(person2.nationality) # 输出:USA
person2.change_nationality('China')
print(person1.nationality) # 输出:China
print(person2.nationality) # 输出:China
```
阅读全文