• Python类的构造方法及继承问题


    构造方法名字固定为__init__,在创建对象时会自动调用,用于实现类的初始化:

    >>> class Person:
    ...     def __init__(self, name, age=0):
    ...             self.name = name
    ...             self.age = age
    ...     def get_name(self):
    ...             return self.name
    ...     def set_name(self, name):
    ...             self.name = name
    ...     def get_age(self):
    ...             return self.age
    ...     def set_age(self, age):
    ...             self.age = age
    ...
    >>> p = Person('韩晓萌','21')
    >>> p.get_name()
    '韩晓萌'
    >>> p.get_age()
    '21'
    >>>

    如果子类重写了__init__方法,那么在方法内必须显式的调用父类的__init__方法:

    # 没有调用父类的__init__方法
    >>> class Man(Person): ... def __init__(self, length): ... self.length = length ... def get_length(self): ... return self.length ... def set_length(self, length): ... self.length = length ... >>> m = Man('18cm') >>> m.get_length() '18cm' >>> m.get_name() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 6, in get_name AttributeError: 'Man' object has no attribute 'name' # 调用了父类的__init__方法 >>> class Woman(Person): ... def __init__(self, name, age=0, cup='A'): ... super().__init__(name, age) ... self.cup = cup ... def get_cup(self): ... return self.cup ... def set_cup(self, cup): ... self.cup = cup ... >>> w = Woman('杨超越', 21, 'C') >>> w.get_cup() 'C' >>> w.get_name() '杨超越' >>> w.get_age() 21
  • 相关阅读:
    Python格式化输出%s和%d
    操作数据库
    协议类介绍
    并发和并行和压测 、对带宽的理解解释
    悠悠大神的 并发当前目录下所有文件的方法(还没试过)
    post参数的方法 json data 和特别的传参
    接口测试简介
    appium的三种等待方式 (还没实践过,记录在此)
    人生进步目标
    保持一个会话 添加 HTTP Cookie管理器
  • 原文地址:https://www.cnblogs.com/hanxiaomeng/p/12711081.html
Copyright © 2020-2023  润新知