4) 声明一个Employee类,其中包括姓名、城市和邮编属性,以及change_name()和display()函数。display()函数显示姓名、城市和邮编属性,change_name()函数实现修改对象的姓名属性。声明包含2个元素的对象数组,每个元素都是Employee类型的对象。给对象赋值并输出。
时间: 2023-06-16 21:04:51 浏览: 118
以下是Employee类的实现代码:
```python
class Employee:
def __init__(self, name, city, zipcode):
self.name = name
self.city = city
self.zipcode = zipcode
def display(self):
print("Name:", self.name)
print("City:", self.city)
print("Zipcode:", self.zipcode)
def change_name(self, new_name):
self.name = new_name
```
然后,我们可以创建一个包含两个元素的Employee对象数组:
```python
emp1 = Employee("Alice", "New York", "10001")
emp2 = Employee("Bob", "San Francisco", "94105")
employees = [emp1, emp2]
```
现在,我们可以使用display()方法输出每个对象的属性:
```python
for emp in employees:
emp.display()
```
输出结果如下:
```
Name: Alice
City: New York
Zipcode: 10001
Name: Bob
City: San Francisco
Zipcode: 94105
```
我们还可以使用change_name()方法来修改其中一个对象的姓名属性:
```python
employees[0].change_name("Alicia")
employees[0].display()
```
输出结果如下:
```
Name: Alicia
City: New York
Zipcode: 10001
```
阅读全文