Inherited class initialization function and basic syntax of Python

Meaning initialization function is that when you create an instance when this function is called.

Writing initialization function is fixed format: the middle is the "init", the Chinese word meaning "initialize" and then two underscores before and after should have [], then __init __ () brackets, the first argument must write on self, or will be error.

Inherit format class is: class new class (the old class), the new class can inherit all the old class methods class, and can be customized new class of old methods and even coverage.

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)

Inherited class initialization function and basic syntax of Python

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='www.linuxidc.com')

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

    def leave(self):  # 子类定制新方法
        print('那个叫“%s”的网站欢迎你的到来。' % self.name)

author1 = Person('Linux公社')
author1.show()
author2 = Man()
author2.show()
author3 = Man()
author3.leave()

Inherited class initialization function and basic syntax of Python

Guess you like

Origin www.linuxidc.com/Linux/2019-06/158959.htm