zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    学习进度第七周
    NABCD---生活日历
    学习进度第六周
    人月神话阅读笔记(3)
    人月神话阅读笔记(2)
    人月神话阅读笔记(1)
    石家庄地铁查询(双人项目)
    学习进度第五周
    学习进度第四周
    返回一个整数数组中最大子数组的和。(续2)---二维数组
  • 原文地址:https://www.cnblogs.com/hanxiaomeng/p/12711081.html
Copyright © 2011-2022 走看看