Python学习之初始化函数和类的继承

初始化函数的意思是,当你创建一个实例的时候,这个函数就会被调用。

初始化函数的写法是固定的格式:中间是“init”,这个单词的中文意思是“初始化”,然后前后都要有【两个下划线】,然后__init__()的括号中,第一个参数一定要写上self,不然会报错。

类的继承格式为:class 新类(旧类),新类就可以继承旧类的所有类方法,并可以定制新的方法甚至覆盖旧类的方法。

练习

class Survey():
    # 收集调查问卷的答案
    def __init__(self, question):
        self.question = question
        self.response = []
    
    # 显示调查问卷的题目
    def show_question(self):
        print(self.question)

    # 存储问卷搜集的答案
    def store_response(self, new_response):
        self.response.append(new_response)

# 请定义实名调查问卷的新类 RealNameSurvey,继承自 Survey 类
class RealNameSurvey(Survey):
    def __init__(self, question):
        Survey.__init__(self, question)
        self.response = {}  # 由于籍贯地和名字挂钩,所以用构成为“键值对”的字典来存放。
    
    # 存储问卷搜集的答案(覆盖父类的类方法)
    def store_response(self, name, new_response):  # 除了 self,还需要两个参数。
        self.response[name] = new_response  # 键值对的新增

survey = RealNameSurvey('你的籍贯地是哪?')
survey.show_question()
while True:
    response = input('请回答问卷问题,按 q 键退出:')
    if response == 'q':
        break
    name = input('请输入回答者姓名:')
    survey.store_response(name, response)  # 调用类方法,将两次通过 input 的字符串存入字典。

# 输出测试
for name, value in survey.response.items():
    print(name + ':' + value)
    
class Survey():
    # 收集调查问卷的答案
    def __init__(self, question):
        self.question = question
        self.response = []
    
    # 显示调查问卷的题目
    def show_question(self):
        print(self.question)

    # 存储问卷搜集的答案
    def store_response(self, new_response):
        self.response.append(new_response)


# 请实例化 Survey() 类,并且显示出这次的调查问卷问题约 2 行代码
food_survey=Survey("你最喜欢的美食是什么")
food_survey.show_question()


# 存储问卷调查的答案
while True:
    response = input('请回答问卷问题,按 q 键退出:')
    if response == 'q':
        break
    
    # 请将答案用问卷系统存储起来,约 1 行代码,变量名见下方。
    food_survey.store_response(response)

# 输出测试
for food in food_survey.response:
    print('美食:' + food)
class Person:
    def __init__(self, name):
        self.name = name
        print('大家注意了!')

    def show(self):
        print('一个叫“%s”的人来了。' % self.name)


class Man(Person):
    def __init__(self):
        Person.__init__(self, name='范罗苏姆')

    def show(self):
        print('一个叫“%s”的男人来了。' % self.name)

    def leave(self):  # 子类定制新方法
        print('那个叫“%s”的男人留下了他的背影。' % self.name)


author1 = Person('吉多')
author1.show()
author2 = Man()
author2.show()
author3 = Man()
author3.leave()

猜你喜欢

转载自blog.csdn.net/qq_42458954/article/details/87559697
今日推荐