用python编写一个歌手类,要求:1.具有姓名、性别和代表作等私有数据成员。2.具有增加、删除代表作等公有方法。3.具有外部属性,用来读写姓名和性别。4.具有外部属性,用来返回代表作
时间: 2024-03-25 18:40:01 浏览: 97
singer-python:从Python编写Singer格式
好的,以下是一个完整的用Python编写的歌手类示例,满足您的要求:
```python
class Singer:
def __init__(self, name, gender, masterpieces=None):
self.__name = name
self.__gender = gender
self.__masterpieces = [] if masterpieces is None else masterpieces
@property
def name(self):
return self.__name
@name.setter
def name(self, new_name):
self.__name = new_name
@property
def gender(self):
return self.__gender
@gender.setter
def gender(self, new_gender):
self.__gender = new_gender
@property
def masterpieces(self):
return self.__masterpieces
def add_masterpiece(self, new_masterpiece):
self.__masterpieces.append(new_masterpiece)
def delete_masterpiece(self, masterpiece):
if masterpiece in self.__masterpieces:
self.__masterpieces.remove(masterpiece)
```
这个歌手类包含了姓名、性别和代表作等私有数据成员,并且具有增加、删除代表作等公有方法。外部属性用来读写姓名和性别,外部属性用来返回代表作。
您可以使用以下代码来创建一个Singer对象并测试它:
```python
# 创建一个Singer对象,并打印它的姓名、性别和代表作
singer = Singer("Taylor Swift", "Female", ["Love Story", "Blank Space"])
print("Singer name:", singer.name)
print("Singer gender:", singer.gender)
print("Singer masterpieces:", singer.masterpieces)
# 修改Singer对象的姓名和性别,并打印修改后的结果
singer.name = "Adele"
singer.gender = "Female"
print("Singer name after modification:", singer.name)
print("Singer gender after modification:", singer.gender)
# 增加和删除Singer对象的代表作,并打印修改后的结果
singer.add_masterpiece("Hello")
singer.delete_masterpiece("Blank Space")
print("Singer masterpieces after modification:", singer.masterpieces)
```
输出结果如下:
```
Singer name: Taylor Swift
Singer gender: Female
Singer masterpieces: ['Love Story', 'Blank Space']
Singer name after modification: Adele
Singer gender after modification: Female
Singer masterpieces after modification: ['Love Story', 'Hello']
```
阅读全文